/* This file contains the eventDispatcher thread code*/

#include "projectHeader.h"

void* eventDispatcher(void *t)
{
	//printf("Inside eventDispatcher thread.\n");
	//pthread_exit(NULL);
	queueItem itemFromQueue;
	while(1)
	{
			//printf("AGAIN WAITING _______________________________________\n");
			memset(&itemFromQueue,0,sizeof(queueItem));
			pthread_mutex_lock(&eventQueueMutex);	
			while ((int)eventQueue.size() == 0 ) 
			{
				pthread_cond_wait(&eventQueueCV, &eventQueueMutex);

			}
			
			 /* dequeue a msg*/ 
			//printf("EVENT DISPATCHER: Pops a message from eventQueue\n");
				
				itemFromQueue=eventQueue.front();
				eventQueue.pop_front();
			pthread_mutex_unlock(&eventQueueMutex);
			queueItem msgToBePushed;
			//printf("Messagetype is: 0X%2X\n",itemFromQueue.msgHeader.messageType);
			if(itemFromQueue.msgHeader.messageType==0xFC)	//Join Req msg.
			{
				//Code to process a msg from queue if it is a JoinReq Msg.
				//printf("EVENT DISPATCHER: Join Req msg detected.\n");
				
				pthread_mutex_lock(&connectedNodeListMutex);
					uint16_t portTemp=0;
					char *tempHost=(char*)malloc(512);
					map<string,int>::iterator it;
				for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
				{
					if((*it).second==itemFromQueue.sockfd)
					{
								char* str1 = (char*) malloc(512); 
								memset(&str1[0],'\0',512);
								memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

								char *str=(char*)malloc(512);
								memset(str,'\0',512);
								memcpy(&str[0],&str1[0],strlen(str1));
								//printf("String from list is %s\n",str);
								
								tempHost=strtok(str,"_");
								//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
								char *tempPort=strtok(NULL,"_");
								//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
								
								portTemp=atoi(tempPort);
								break;
					}
				
				}
				pthread_mutex_unlock(&connectedNodeListMutex);


					pthread_mutex_lock(&logFileMutex);
					uint16_t tempport=0;
						memcpy(&tempport,&itemFromQueue.dataBuf[4],sizeof(uint16_t));
						char temphost1[20];
						memset(&temphost1[0],'\0',20);
						memcpy(&temphost1[0],&itemFromQueue.dataBuf[6],strlen(myHostName));

					gettimeofday(&tv, NULL); 
					int sec = tv.tv_sec ;
					int msec = tv.tv_usec/1000;
					char *time = (char *)malloc(14);
					memset(time,0,14);
					sprintf(time,"%10ld.%03d",(long)sec,msec);
					time[strlen(time)]='\0';
					fprintf(logFilePtr, "r  %s %s:%hu JNRQ %d 0x%02x %x%x%x%x %hu %s\n",time,
							tempHost, portTemp,
							(itemFromQueue.msgHeader.msgDataLength+27),
							(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
							(unsigned char)itemFromQueue.msgHeader.UOID[16],
							(unsigned char)itemFromQueue.msgHeader.UOID[17],
							(unsigned char)itemFromQueue.msgHeader.UOID[18],
							(unsigned char)itemFromQueue.msgHeader.UOID[19],
							tempport,temphost1);
					pthread_mutex_unlock(&logFileMutex);
					






				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator=UOIDMsgLifeTimeMap.find(str);

				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{

						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));

						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
						//Make a new item to be pushed on all queues.
						//printf("---------------1--------------\n");
						

						msgToBePushed.sockfd=itemFromQueue.sockfd;
						//populate the header as the same only changing the TTL value.
						msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
						memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
						//Decrease TTL by 1 is ttl in header less than node ttl
						//else set node ttl as the new ttl ..
						if((itemFromQueue.msgHeader.ttlInHeader-1)<ttl)
						{
							msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
						}
						else
						{
							msgToBePushed.msgHeader.ttlInHeader=ttl;	
						}

						msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
						//Copy Data from itemfromqueue into new quueue item.
						memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
						//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
						//forward the msg to other nodes if the new ttl>0
						if(msgToBePushed.msgHeader.ttlInHeader!=0)
						{
							//Find index of writeQueue from map for all entries in connectedNodeList
							map<string,int>::iterator conNodeListIterator;
							//printf("---------------2--------------\n");
							pthread_mutex_lock(&connectedNodeListMutex);
							//printf("---------------4--------------\n");
							for ( conNodeListIterator=connectedNodeList.begin() ; conNodeListIterator != connectedNodeList.end(); conNodeListIterator++ )
							{

								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);

								//printf("---------------5--------------\n");
								int socket=(*conNodeListIterator).second;
								//printf("---------------5--------------%d\n",socket);
								if(socket!=itemFromQueue.sockfd)
								{
									//printf("---------------6--------------\n");
									pthread_mutex_lock(&sockIndexMapMutex);
									int index=sockFDToQIndexMap[socket];
										pthread_mutex_lock(&wrtieQMutex[index]);
										//	printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
											wrtieThreadQueue[index].push_back(msgToBePushed);
											//printf("EVENT DISPATCHER: JOIN MSG: Msg pushed to writeQueue of %d\n",index);
											pthread_cond_broadcast(&wrtieQCV[index]);

										pthread_mutex_unlock(&wrtieQMutex[index]);								
									pthread_mutex_unlock(&sockIndexMapMutex);

								//}
								//printf("---------------7--------------\n");
							//}
					
								char* str1 = (char*) malloc(512); 
								memset(&str1[0],'\0',512);
								memcpy(&str1[0],&(((*conNodeListIterator).first).c_str()[0]),19);

								char *str=(char*)malloc(512);
								memset(str,'\0',512);
								memcpy(&str[0],&str1[0],strlen(str1));
								//printf("String from list is %s\n",str);
								
								tempHost=strtok(str,"_");
								//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
								char *tempPort=strtok(NULL,"_");
								//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
								
								portTemp=atoi(tempPort);
								
								//}




							pthread_mutex_lock(&logFileMutex);
							uint16_t tempport=0;
							memcpy(&tempport,&itemFromQueue.dataBuf[4],sizeof(uint16_t));
							char temphost1[20];
							memset(&temphost1[0],'\0',20);
							memcpy(&temphost1[0],&itemFromQueue.dataBuf[6],strlen(myHostName));

							gettimeofday(&tv, NULL); 
							int sec = tv.tv_sec ;
							int msec = tv.tv_usec/1000;
							char *time = (char *)malloc(14);
							memset(time,0,14);
							sprintf(time,"%10ld.%03d",(long)sec,msec);
							time[strlen(time)]='\0';
							fprintf(logFilePtr, "f  %s %s:%hu JNRQ %d 0x%02x %x%x%x%x %hu %s\n",time,
									tempHost, portTemp,
									(msgToBePushed.msgHeader.msgDataLength+27),
									(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
									(unsigned char)msgToBePushed.msgHeader.UOID[16],
									(unsigned char)msgToBePushed.msgHeader.UOID[17],
									(unsigned char)msgToBePushed.msgHeader.UOID[18],
									(unsigned char)msgToBePushed.msgHeader.UOID[19],
									tempport,temphost1);
							pthread_mutex_unlock(&logFileMutex);
								}
							}






							pthread_mutex_unlock(&connectedNodeListMutex);
						}



















				//Now populate the JoinResponse msg and push it to the queue..
				queueItem joinResp;
				uint32_t peerLocValue=-1;
				uint32_t computedDist=0;
				memcpy(&peerLocValue,msgToBePushed.dataBuf,4);
				if(peerLocValue<location)
				{
					computedDist=location-peerLocValue;
				}
				else
				{
					computedDist=peerLocValue-location;
				}
				joinResp.sockfd=itemFromQueue.sockfd;

				joinResp.msgHeader.messageType=0xFB;
				unsigned char *buff1;
				char* msg = (char*)"JNRS";

				//printf("NodeID is %s\n",nodeInstanceId);
	
				buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
				memcpy(joinResp.msgHeader.UOID,buf,20);
				
				joinResp.msgHeader.ttlInHeader=ttl;	
				joinResp.msgHeader.msgDataLength=20+sizeof(uint32_t)+sizeof(uint16_t)+strlen(myHostName);
				
				//Populate the joinRespDataBuf.
				
				joinRespMsgDataClass joinRespData;
				char *joinRespDataBuf=new char[512];
				//memset(joinRespDataBuf,'-',512);
				/*
				memcpy(joinRespDataBuf,itemFromQueue.msgHeader.UOID,20);
				//memcpy(joinRespDataBuf+20,&computedDist,4);
				memcpy(joinRespDataBuf+20,&port,2);
				memcpy(joinRespDataBuf+22,myHostName,strlen(myHostName));
				*/
				//computedDist=0xFFFFFFFF;
				uint32_t computedDist1;
				memcpy(&joinRespDataBuf[0],itemFromQueue.msgHeader.UOID,20);
				memcpy(&joinRespDataBuf[20],&htonl(computedDist),sizeof(uint32_t));
				memcpy(&computedDist1,&joinRespDataBuf[20],sizeof(uint32_t));
				

				//printf("Buffer is: [%s]\n",joinRespDataBuf);

				//printf("NEW VALUE: %lu",computedDist1);
				//memcpy(&joinRespDataBuf[20],(void*)htonl("200"),sizeof(uint32_t));
				memcpy(&joinRespDataBuf[24],&port,sizeof(uint16_t));
				memcpy(&joinRespDataBuf[26],myHostName,strlen(myHostName));
				//printf("\n[%X,%X,%X,%X,%X,%c]\n",joinRespDataBuf[19],joinRespDataBuf[20],joinRespDataBuf[21],joinRespDataBuf[22],joinRespDataBuf[23],joinRespDataBuf[38]);
				//printf("Size of the buffer is %d",(int)strlen(joinRespDataBuf));
				//copy temp buf to queueitem databuf
				memcpy(&joinResp.dataBuf[0],joinRespDataBuf,joinResp.msgHeader.msgDataLength);
				
				delete[] joinRespDataBuf;
				//Push the item in proper write Queue.
				pthread_mutex_lock(&sockIndexMapMutex);
				int index=sockFDToQIndexMap[itemFromQueue.sockfd];
					pthread_mutex_lock(&wrtieQMutex[index]);
						wrtieThreadQueue[index].push_back(joinResp);
						//printf("EVENT DISPATCHER: JOIN RESPONSE MSG: Msg pushed to writeQueue of %d\n",index);
						pthread_cond_broadcast(&wrtieQCV[index]);

					pthread_mutex_unlock(&wrtieQMutex[index]);								
				pthread_mutex_unlock(&sockIndexMapMutex);
				
				pthread_mutex_lock(&connectedNodeListMutex);
				uint16_t portTemp=0;
				char *tempHost=(char*)malloc(512);
				map<string,int>::iterator it;
				for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
				{
					if((*it).second==itemFromQueue.sockfd)
					{
								char* str1 = (char*) malloc(512); 
								memset(&str1[0],'\0',512);
								memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

								char *str=(char*)malloc(512);
								memset(str,'\0',512);
								memcpy(&str[0],&str1[0],strlen(str1));
								//printf("String from list is %s\n",str);
								
								tempHost=strtok(str,"_");
								//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
								char *tempPort=strtok(NULL,"_");
								//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
								
								portTemp=atoi(tempPort);
								break;
					}
				
				}
				pthread_mutex_unlock(&connectedNodeListMutex);







				pthread_mutex_lock(&logFileMutex);

				gettimeofday(&tv, NULL); 
				int sec = tv.tv_sec ;
				int msec = tv.tv_usec/1000;
				char *time = (char *)malloc(14);
				memset(time,0,14);
				sprintf(time,"%10ld.%03d",(long)sec,msec);
				time[strlen(time)]='\0';
				fprintf(logFilePtr, "s  %s %s:%hu JNRS %d 0x%02x %x%x%x%x %x%x%x%x %d %hu %s\n",time,
					tempHost,
					portTemp,
					(joinResp.msgHeader.msgDataLength+27),
					(unsigned char)joinResp.msgHeader.ttlInHeader,
					(unsigned char)joinResp.msgHeader.UOID[16],
					(unsigned char)joinResp.msgHeader.UOID[17],
					(unsigned char)joinResp.msgHeader.UOID[18],
					(unsigned char)joinResp.msgHeader.UOID[19],
					(unsigned char)itemFromQueue.msgHeader.UOID[16],
					(unsigned char)itemFromQueue.msgHeader.UOID[17],
					(unsigned char)itemFromQueue.msgHeader.UOID[18],
					(unsigned char)itemFromQueue.msgHeader.UOID[19],
					computedDist,
					port,myHostName);
				pthread_mutex_unlock(&logFileMutex);











				//printf("---------------3--------------\n");
				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:JOIN REQUEST The msg already exists in the map.DO NOT FORWARD!!!!\n");
					continue;
				}



			}//end of JOIN REQ MSG
			else if(itemFromQueue.msgHeader.messageType==0xFB)       //JOIN RESPONSE MSG
			{
				//printf("EVENT DISPATCHER: Join Resp msg detected.\n");
				
				pthread_mutex_lock(&connectedNodeListMutex);
				uint16_t portTemp=0;
				char *tempHost=(char*)malloc(512);
				map<string,int>::iterator it;
				for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
				{
					if((*it).second==itemFromQueue.sockfd)
					{
								char* str1 = (char*) malloc(512); 
								memset(&str1[0],'\0',512);
								memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

								char *str=(char*)malloc(512);
								memset(str,'\0',512);
								memcpy(&str[0],&str1[0],strlen(str1));
								//printf("String from list is %s\n",str);
								
								tempHost=strtok(str,"_");
								//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
								char *tempPort=strtok(NULL,"_");
								//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
								
								portTemp=atoi(tempPort);
								break;
					}
				
				}
				pthread_mutex_unlock(&connectedNodeListMutex);

						pthread_mutex_lock(&logFileMutex);
						uint32_t dist=0;
						memcpy(&dist,&itemFromQueue.dataBuf[20],sizeof(uint32_t));
						uint16_t tempport=0;
						memcpy(&tempport,&itemFromQueue.dataBuf[24],sizeof(uint16_t));
						char temphost1[20];
						memset(&temphost1[0],'\0',20);
						memcpy(&temphost1[0],&itemFromQueue.dataBuf[26],strlen(myHostName));

						gettimeofday(&tv, NULL); 
						int sec = tv.tv_sec ;
						int msec = tv.tv_usec/1000;
						char *time = (char *)malloc(14);
						memset(time,0,14);
						sprintf(time,"%10ld.%03d",(long)sec,msec);
						time[strlen(time)]='\0';
						fprintf(logFilePtr, "r  %s %s:%hu JNRS %d 0x%02x %x%x%x%x %x%x%x%x %d %hu %s\n",time,
							tempHost,
							portTemp,
							(itemFromQueue.msgHeader.msgDataLength+27),
							(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
							(unsigned char)itemFromQueue.msgHeader.UOID[16],
							(unsigned char)itemFromQueue.msgHeader.UOID[17],
							(unsigned char)itemFromQueue.msgHeader.UOID[18],
							(unsigned char)itemFromQueue.msgHeader.UOID[19],
							(unsigned char)itemFromQueue.dataBuf[16],
							(unsigned char)itemFromQueue.dataBuf[17],
							(unsigned char)itemFromQueue.dataBuf[18],
							(unsigned char)itemFromQueue.dataBuf[19],
							dist,
							tempport,temphost1);
						pthread_mutex_unlock(&logFileMutex);












				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);
				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator=UOIDMsgLifeTimeMap.find(str);
				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{	

						//Entry not found in the map.. make a new entry in the map for it. and continue to process the msg.
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string, msgLifeTimeClass>(uoid, newEntry));
						

						unsigned char uoidFromItemData[20];
						memcpy(&uoidFromItemData[0],&(itemFromQueue.dataBuf[0]),20);
						string str1 ((const char*)uoidFromItemData,20);
						uoidIterator=UOIDMsgLifeTimeMap.find(str1);

						if(uoidIterator==UOIDMsgLifeTimeMap.end())
						{
						
							//NOT FOUND
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							//printf("EVENT DISPATCHER: JOIN RESPONSE. THERE HAS NOT BEEN ANY JOIN REQ FOR THIS UOID.\n\n");
						
						}
						else
						{
							//Found in the UOID MAP.
							int index=-1;

							



							msgLifeTimeClass tmp=(*uoidIterator).second;
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);

							pthread_mutex_lock(&sockIndexMapMutex);
								 index=sockFDToQIndexMap[tmp.sockOfMsgReciept];
								 pthread_mutex_lock(&wrtieQMutex[index]);
										//printf("EVENT DISPATCHER: JOIN RESP msgtype %x and buffer is %s",msgToBePushed.msgHeader,);
										wrtieThreadQueue[index].push_back(itemFromQueue);
										//printf("EVENT DISPATCHER: JOIN RESP: Msg pushed to writeQueue of %d\n",index);
										pthread_cond_broadcast(&wrtieQCV[index]);

								pthread_mutex_unlock(&wrtieQMutex[index]);	
							pthread_mutex_unlock(&sockIndexMapMutex);

							
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==tmp.sockOfMsgReciept)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

						pthread_mutex_lock(&logFileMutex);
						
						gettimeofday(&tv, NULL); 
						int sec = tv.tv_sec ;
						int msec = tv.tv_usec/1000;
						char *time = (char *)malloc(14);
						memset(time,0,14);
						sprintf(time,"%10ld.%03d",(long)sec,msec);
						time[strlen(time)]='\0';
						fprintf(logFilePtr, "f  %s %s:%hu JNRS %d 0x%02x %x%x%x%x %x%x%x%x %d %hu %s\n",time,
							tempHost,
							portTemp,
							(itemFromQueue.msgHeader.msgDataLength+27),
							(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
							(unsigned char)itemFromQueue.msgHeader.UOID[16],
							(unsigned char)itemFromQueue.msgHeader.UOID[17],
							(unsigned char)itemFromQueue.msgHeader.UOID[18],
							(unsigned char)itemFromQueue.msgHeader.UOID[19],
							(unsigned char)itemFromQueue.dataBuf[16],
							(unsigned char)itemFromQueue.dataBuf[17],
							(unsigned char)itemFromQueue.dataBuf[18],
							(unsigned char)itemFromQueue.dataBuf[19],
							dist,
							tempport,temphost1);
						pthread_mutex_unlock(&logFileMutex);









						}





				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:JOIN RESPONSE The msg already exists in the map.DO NOT FORWARD!!!!\n");
					//exit(0);
					continue;  //Think abt this. Whether to put continue or exit(0);
				}

			
				

				

			}//END OF JOIN RESPONSE MSG
			else if(itemFromQueue.msgHeader.messageType==0xF7) //NOTIFY MESSAGE
			{
				
				
				char errorCode= '\0';
				memcpy(&errorCode,&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
				//printf("EVENT DISPATCHER: NOTIFY msg detected with ErrorCode %c\n",errorCode);
				//close the connection with that node.


			pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
													memset(&str1[0],'\0',512);
													memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

													char *str=(char*)malloc(512);
													memset(str,'\0',512);
													memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);



				pthread_mutex_lock(&logFileMutex);

				gettimeofday(&tv, NULL); 
				int sec = tv.tv_sec ;
				int msec = tv.tv_usec/1000;
				char *time = (char *)malloc(14);
				memset(time,0,14);
				sprintf(time,"%10ld.%03d",(long)sec,msec);
				time[strlen(time)]='\0';

				



				fprintf(logFilePtr, "r  %s %s:%hu NTFY %d 0x%02x %x%x%x%x %c\n",time,
					tempHost,
					portTemp,
					(itemFromQueue.msgHeader.msgDataLength+27),
					(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
					(unsigned char)itemFromQueue.msgHeader.UOID[16],
					(unsigned char)itemFromQueue.msgHeader.UOID[17],
					(unsigned char)itemFromQueue.msgHeader.UOID[18],
					(unsigned char)itemFromQueue.msgHeader.UOID[19],itemFromQueue.dataBuf[0]);
					//helloRecvData.HostPort,helloRecvData.Hostname);
				pthread_mutex_unlock(&logFileMutex);















				pthread_mutex_lock(&connectedNodeListMutex);
				pthread_mutex_lock(&sockIndexMapMutex);
			
					map<int,int>:: iterator temp2;
					int mapIndex=sockFDToQIndexMap[itemFromQueue.sockfd];
					map<int,int>:: iterator temp3;
					temp3=keepAliveTimers.find(mapIndex);
					temp2 = sockFDToQIndexMap.find(itemFromQueue.sockfd);
					//int timer=(*temp3).second;
					//printf("\n############################%d----%d############################\n",mapIndex,timer);
					//for(temp2=sockFDToQIndexMap.begin();temp2!=sockFDToQIndexMap.end();temp2++)
					//{
					//	int socket=(*temp2).first;
					//	if(socket == itemFromQueue.sockfd)
					//	{
							sockFDToQIndexMap.erase(temp2);
							keepAliveTimers.erase(temp3);
							//erase from connectedNodeList map
						
							
					//	}

						
					//}
					map<string,int>:: iterator temp4;
							for(temp4=connectedNodeList.begin();temp4!=connectedNodeList.end();temp4++)
							{
								if((*temp4).second== itemFromQueue.sockfd)
								{
									//printf("\nTimeout for socket : %d... hostString is %s and map socket is : %d....\n",socket,(*temp4).first.c_str(),(*temp4).second);
									connectedNodeList.erase(temp4);
								}
							}

							//pthread_cancel read and write thread.
							pthread_cancel(readBeacon[mapIndex]);
							pthread_cancel(writeBeacon[mapIndex]);	

							//erase from wQueueIndexBitMap map
							//wQueueIndexBitMap.set(mapIndex,0);

							close(itemFromQueue.sockfd);
				
				pthread_mutex_unlock(&sockIndexMapMutex);
				pthread_mutex_unlock(&connectedNodeListMutex);
				
				//If i am not beacon then only, push check message to the eventqueue.
				if(!iAmBeacon)
				{
					queueItem statusReqToBePushed;
					statusReqToBePushed.sockfd=-1;
					statusReqToBePushed.msgHeader.messageType=0xF6;

					unsigned char *buff1;
					char* msg = (char*)"CKRQ";

					buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
					memcpy(&(statusReqToBePushed.msgHeader.UOID[0]),&buf[0],20);

					statusReqToBePushed.msgHeader.ttlInHeader=ttl;
					statusReqToBePushed.msgHeader.msgDataLength=0;

					//memcpy(&(statusReqToBePushed.dataBuf[0]),&(statusData.statusType),statusReqToBePushed.msgHeader.msgDataLength);

					
					//check timeout thread start
					if(noCheck==0)
					{
						pthread_create(&checkTimeOut,NULL,checkTimeOutThread,NULL);
						
						
						pthread_mutex_lock(&eventQueueMutex);


					eventQueue.push_back(statusReqToBePushed);
					//printf("EVENT DISPATCHER:CHECK MSG Pushed to Event Dispatcher.\n");
					pthread_cond_broadcast(&eventQueueCV);


					pthread_mutex_unlock(&eventQueueMutex);

						//join this thread
						pthread_join(checkTimeOut,NULL);
					}

				}
				
				
			}// END NOTIFY MESSAGE...
			else if(itemFromQueue.msgHeader.messageType==0xAC)       //STATUS REQ MSG
			{
				//printf("EVENT DISPATCHER: STATUS REQ MSD detected.\n");
				

				if(itemFromQueue.sockfd!=-1)
				{
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);
				pthread_mutex_lock(&logFileMutex);

				gettimeofday(&tv, NULL); 
				int sec = tv.tv_sec ;
				int msec = tv.tv_usec/1000;
				char *time = (char *)malloc(14);
				memset(time,0,14);
				sprintf(time,"%10ld.%03d",(long)sec,msec);
				time[strlen(time)]='\0';

				



				fprintf(logFilePtr, "r  %s %s:%hu STRQ %d 0x%02x %x%x%x%x 0x01\n",time,
					tempHost,
					portTemp,
					(itemFromQueue.msgHeader.msgDataLength+27),
					(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
					(unsigned char)itemFromQueue.msgHeader.UOID[16],
					(unsigned char)itemFromQueue.msgHeader.UOID[17],
					(unsigned char)itemFromQueue.msgHeader.UOID[18],
					(unsigned char)itemFromQueue.msgHeader.UOID[19]);
					//helloRecvData.HostPort,helloRecvData.Hostname);
				pthread_mutex_unlock(&logFileMutex);
				
				}













//printf("------1--------\n");

				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);

				uoidIterator=UOIDMsgLifeTimeMap.find(str);
				
				//printf("UOID recieved:");
				//printUOID((unsigned char*)str.c_str());
				//map<string,msgLifeTimeClass>::iterator uoidIterator9;
				//printf("UOID MAP is :");
				//for(uoidIterator9=UOIDMsgLifeTimeMap.begin();uoidIterator9!=UOIDMsgLifeTimeMap.end();uoidIterator9++)
				//{
					//printUOID( (unsigned char*)((*uoidIterator9).first).c_str());
			//	}
				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));

						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
								

						msgToBePushed.sockfd=itemFromQueue.sockfd;
						//populate the header as the same only changing the TTL value.
						msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
						memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
						//Decrease TTL by 1 is ttl in header less than node ttl
						//else set node ttl as the new ttl ..
						//printf("------2--------\n");
						//printf("---------------%d-----char %c--%x-------\n",itemFromQueue.msgHeader.ttlInHeader,itemFromQueue.msgHeader.ttlInHeader-1,  itemFromQueue.msgHeader.ttlInHeader);
						if(itemFromQueue.sockfd!=-1)
						{
							if((itemFromQueue.msgHeader.ttlInHeader-1)<(char)ttl)
							{
								//printf("code is here.\n");
								msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
							}
							else
							{
								//printf("WTF\n");
								msgToBePushed.msgHeader.ttlInHeader=ttl;	
							}
						}
						else
						{
							msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader;
						}
						msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
						//Copy Data from itemfromqueue into new quueue item.
						memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
						//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
						//forward the msg to other nodes if the new ttl>0
						
						if(msgToBePushed.msgHeader.ttlInHeader>0)
						{

							
							//Find index of writeQueue from map for all entries in connectedNodeList
							map<string,int>::iterator conNodeListIterator2;
							//printf("---------------3--------------\n");
							pthread_mutex_lock(&connectedNodeListMutex);
							//printf("---------------4--------------\n");
							for ( conNodeListIterator2=connectedNodeList.begin() ; conNodeListIterator2 != connectedNodeList.end(); conNodeListIterator2++ )
							{

								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								//printf("---------------5--------------\n");
								int socket=(*conNodeListIterator2).second;
								//printf("---------------5--------------%d\n",socket);
								if(socket!=itemFromQueue.sockfd)
								{
									//printf("---------------4--------------\n");
									pthread_mutex_lock(&sockIndexMapMutex);
									int index=sockFDToQIndexMap[socket];
										pthread_mutex_lock(&wrtieQMutex[index]);
										//	//printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
											wrtieThreadQueue[index].push_back(msgToBePushed);
											//printf("EVENT DISPATCHER: STATUS REQ MSG: Msg pushed to writeQueue of %d\n",index);
											pthread_cond_broadcast(&wrtieQCV[index]);

										pthread_mutex_unlock(&wrtieQMutex[index]);								
									pthread_mutex_unlock(&sockIndexMapMutex);

									//char* str1 = (char*)((*conNodeListIterator2).first).c_str();	
											char* str1 = (char*) malloc(512); 
											memset(&str1[0],'\0',512);
											memcpy(&str1[0],&(((*conNodeListIterator2).first).c_str()[0]),19);

											char *str=(char*)malloc(512);
											memset(str,'\0',512);
											memcpy(&str[0],&str1[0],strlen(str1));
										//printf("String from list is %s\n",str);
										
										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										
										portTemp=atoi(tempPort);
										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										

							//			printf("\n{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}\n");


										fprintf(logFilePtr, "f  %s %s:%hu STRQ %d 0x%02x %x%x%x%x 0x01\n",time,
											tempHost,
											portTemp,
											(msgToBePushed.msgHeader.msgDataLength+27),
											(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
											(unsigned char)msgToBePushed.msgHeader.UOID[16],
											(unsigned char)msgToBePushed.msgHeader.UOID[17],
											(unsigned char)msgToBePushed.msgHeader.UOID[18],
											(unsigned char)msgToBePushed.msgHeader.UOID[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);



								}
								//printf("---------------7--------------\n");
							}
							pthread_mutex_unlock(&connectedNodeListMutex);
						}


						if(itemFromQueue.sockfd==-1)
						{
							//The eventdispatcher that poped the msg is at the same node as the terminal where status msg was requested.
							// So add the list of neighbors for the current node the the datalist that will be written into the NAM file.
							//printf("I am where status req started.\n");
							if(itemFromQueue.dataBuf[0]==0x01)
							{
									map<string,int>::iterator conNodeListIterator5;
									pthread_mutex_lock(&connectedNodeListMutex);
									list<int> tempPortListToInsertInMap;
									for(conNodeListIterator5=connectedNodeList.begin();conNodeListIterator5!=connectedNodeList.end();conNodeListIterator5++ )
									{
										char* str1 = (char*)((*conNodeListIterator5).first).c_str();	
										char *str=(char*)malloc(512);
										memset(str,'\0',512);
										memcpy(&str[0],&str1[0],strlen(str1));
										char *tempHost=NULL;
										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										int portTemp=0;
										
										portTemp=atoi(tempPort);
										tempPortListToInsertInMap.push_back(portTemp);
										//printf("Port %d pushed in list for mapkey %d\n",portTemp,(int)port);
									
									}
									pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
									statusRespMap.insert(pair<int,list<int> >((int)port,tempPortListToInsertInMap));
									}
									pthread_mutex_unlock(&cntrlCFlagMutex);
									pthread_mutex_unlock(&connectedNodeListMutex);
							}
							else if (itemFromQueue.dataBuf[0]==0x02)
							{
								//TODO: Write the status file data for the req initiating node.
								
								char statusFileWriteBuf[8192];
								
								pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
										pthread_mutex_lock(&statusFileWriteLock);
										FILE *statusOutfile = fopen(statusFileName,"w");
										if(numToFileIdMap.size() == 0)
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has no file\n",port);
										}
										else if (numToFileIdMap.size() == 1)
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has the following file\n",port);
										}
										else
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has the following files\n",port);
										}
										map<int,string>::iterator it10;
										pthread_mutex_lock(&indexMutex);

										for(it10=numToFileIdMap.begin();it10!=numToFileIdMap.end();it10++)
										{
											memset(&statusFileWriteBuf[0],'\0',8192);
											int numericId= (*it10).first;
											char appendMFileName[256];
											memset(&appendMFileName[0],'\0',256);
											sprintf(appendMFileName, "/%d.meta", numericId);

											char newNumMetaFile[256];
											memset(newNumMetaFile, '\0', 256);	
											memcpy(newNumMetaFile,homeDir,strlen(homeDir));
											strcat(newNumMetaFile,"/files");
											strcat(newNumMetaFile,appendMFileName);

											struct stat statistics1;
											int status1;
											status1 = stat((char*)newNumMetaFile,&statistics1);
											if(status1<0)
											{
												//printf("File does not exist.\n");

											}
											unsigned int metaFileSize = statistics1.st_size;
											if(!(status1<0))
											{
											FILE* temp= fopen(newNumMetaFile,"r");
											int read=0;
											
											 read = fread(statusFileWriteBuf,1,metaFileSize,temp);	
											
											if(read == -1)
											{
												
												//printf("EVENT DISPATCHER: Error Reading META FILE\n");
											}
											fclose(temp);	
											fprintf(statusOutfile,"%s",statusFileWriteBuf);
											fprintf(statusOutfile,"\n");
											}


										}

									




										fclose(statusOutfile);
										pthread_mutex_unlock(&indexMutex);

										pthread_mutex_unlock(&statusFileWriteLock);
					
					//		printf("Status File Output written for own files.\n");
									}
								pthread_mutex_unlock(&cntrlCFlagMutex);
									

							}
							else
							{
								//printf("Wrong message type detected on status req packet..\n");
							}




						}
						else// the status req recieved is from some other node.. so send him the status response packet.
						{

							queueItem statusRespToBePushed;
							statusRespToBePushed.sockfd=itemFromQueue.sockfd;
							statusRespToBePushed.msgHeader.messageType=0xAB;
							unsigned char *buff1;
							char* msg = (char*)"STRS";
							
							buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
							memcpy(&(statusRespToBePushed.msgHeader.UOID[0]),&buf[0],20);

							statusRespToBePushed.msgHeader.ttlInHeader=ttl;

							statusRespClass statusRespData;
							memcpy(&(statusRespData.UOID),&(itemFromQueue.msgHeader.UOID),20);
							statusRespData.HostPort=port;
							memcpy(&(statusRespData.Hostname[0]),myHostName,strlen(myHostName));
							statusRespData.HostInfoLength=sizeof(statusRespData.HostPort)+strlen(statusRespData.Hostname);
							
							
							char respBuf[8192];
							memset(&(respBuf[0]),'\0',8192);

							memcpy(&(respBuf[0]),&(statusRespData.UOID),20);
							memcpy(&(respBuf[20]),&(statusRespData.HostInfoLength),2);
							memcpy(&(respBuf[22]),&(statusRespData.HostPort),2);
							memcpy(&(respBuf[24]),&(statusRespData.Hostname[0]),strlen(myHostName));
							
							int datalength= sizeof(statusRespData.HostPort)+strlen(statusRespData.Hostname)+sizeof(statusRespData.HostInfoLength)+20;
							int tempdatalength=0;
							if(itemFromQueue.dataBuf[0]==0x01)
							{
									map<string,int>::iterator conNodeListIterator1;
									pthread_mutex_lock(&connectedNodeListMutex);
									for(conNodeListIterator1=connectedNodeList.begin();conNodeListIterator1!=connectedNodeList.end();conNodeListIterator1++ )
									{
										char* str1 = (char*)((*conNodeListIterator1).first).c_str();	

										char *str=(char*)malloc(512);
										memset(str,'\0',512);
										memcpy(&str[0],&str1[0],strlen(str1));
										//printf("String from list is %s\n",str);
										char *tempHost=NULL;
										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										uint16_t portTemp=0;
										portTemp=atoi(tempPort);
										//printf("String from list is %s\n",(char*)((*conNodeListIterator1).first).c_str());
										uint32_t recordLength=strlen(tempHost)+2;
										memcpy(&(respBuf[datalength]),&recordLength,4);
										memcpy(&(respBuf[datalength+4]),&portTemp,2);
										memcpy(&(respBuf[datalength+6]),&tempHost,strlen(tempHost));

										
									

										
										datalength+=(recordLength+4);

									
									}
									pthread_mutex_unlock(&connectedNodeListMutex);
									
								}
								else if(itemFromQueue.dataBuf[0]==0x02)
								{
									// TODO:Write the status files resp buffer for the current node.
									//char statusFileWriteBuf[8192];
								

									
									map<int,string>::iterator it10;
									pthread_mutex_lock(&indexMutex);
									//memset(&statusFileWriteBuf[0],'\0',8192);

									int totalSize=0;
									tempdatalength=datalength;
									
									for(it10=numToFileIdMap.begin();it10!=numToFileIdMap.end();it10++)
									{
										//printf("Inside the iteraator.\n\n");
										int numericId= (*it10).first;
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numericId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(&respBuf[datalength+4],1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
										memset(&respBuf[datalength+metaFileSize+4],'\n',1);
										totalSize+=(metaFileSize+1);
										datalength+=(metaFileSize+1);
										fclose(temp);	
										//fprintf(statusOutfile,"%s",statusFileWriteBuf);
									}
									pthread_mutex_unlock(&indexMutex);
									memcpy(&(respBuf[tempdatalength]),&totalSize,4);
									datalength+=4;
								//	printf("Status File Output written for status request at %d.\n",port);
								}
								//fclose(statusOutfile);
								
								//pthread_mutex_unlock(&statusFileWriteLock);


								else
								{
										//printf("Wrong message type detected on status req packet..\n");
								}



							
							memcpy(&(statusRespToBePushed.dataBuf[0]),&(respBuf[0]),datalength);
							statusRespToBePushed.msgHeader.msgDataLength=datalength;
						//	printf("DATA LENGTH OF STATIS RESP is %d\n",datalength);
							//printf("MSG Populated is %s\n",statusRespToBePushed.dataBuf);
							pthread_mutex_lock(&sockIndexMapMutex);
							int index=sockFDToQIndexMap[itemFromQueue.sockfd];
								pthread_mutex_lock(&wrtieQMutex[index]);
									wrtieThreadQueue[index].push_back(statusRespToBePushed);
									//printf("EVENT DISPATCHER: STATUS RESPONSE MSG: Msg pushed to writeQueue of %d\n",index);
									pthread_cond_broadcast(&wrtieQCV[index]);

								pthread_mutex_unlock(&wrtieQMutex[index]);								
							pthread_mutex_unlock(&sockIndexMapMutex);


						pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
													memset(&str1[0],'\0',512);
													memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

													char *str=(char*)malloc(512);
													memset(str,'\0',512);
													memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "s  %s %s:%hu STRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(statusRespToBePushed.msgHeader.msgDataLength+27),
											(unsigned char)statusRespToBePushed.msgHeader.ttlInHeader,
											(unsigned char)statusRespToBePushed.msgHeader.UOID[16],
											(unsigned char)statusRespToBePushed.msgHeader.UOID[17],
											(unsigned char)statusRespToBePushed.msgHeader.UOID[18],
											(unsigned char)statusRespToBePushed.msgHeader.UOID[19],
											(unsigned char)statusRespToBePushed.dataBuf[16],
											(unsigned char)statusRespToBePushed.dataBuf[17],
											(unsigned char)statusRespToBePushed.dataBuf[18],
											(unsigned char)statusRespToBePushed.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);














						
						}



				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:STATUS REQUEST The msg already exists in the map.DO NOT FORWARD!!!!\n");
					continue;
				}







			
			}
			else if(itemFromQueue.msgHeader.messageType==0xAB)       //STATUS RESP MSG
			{
				//printf("Status Resp msg detected.\n");

				
				

							pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "r  %s %s:%hu STRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);












				map<string,msgLifeTimeClass>::iterator uoidIterator2;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator2=UOIDMsgLifeTimeMap.find(str);
				if(uoidIterator2 == UOIDMsgLifeTimeMap.end())
				{	

						//Entry not found in the map.. make a new entry in the map for it. and continue to process the msg.
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string, msgLifeTimeClass>(uoid, newEntry));
						

						unsigned char uoidFromItemData[20];
						memcpy(&uoidFromItemData[0],&(itemFromQueue.dataBuf[0]),20);
						string str1 ((const char*)uoidFromItemData,20);
						uoidIterator2=UOIDMsgLifeTimeMap.find(str1);

						if(uoidIterator2==UOIDMsgLifeTimeMap.end())
						{
						
							//NOT FOUND
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							//printf("EVENT DISPATCHER: STATUS RESPONSE. THERE HAS NOT BEEN ANY STATUS REQ FOR THIS UOID.\n\n");
						
						}
						else
						{
							//Found in the UOID MAP.
							int index=-1;
							msgLifeTimeClass tmp=(*uoidIterator2).second;
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							if(tmp.sockOfMsgReciept== -1)
							{
								
								statusRespClass statusRespToBeProcessed;
								memcpy(&(statusRespToBeProcessed.UOID[0]),&(itemFromQueue.dataBuf[0]),20);
								memcpy(&statusRespToBeProcessed.HostInfoLength,&(itemFromQueue.dataBuf[20]),2);
								//memcpy(&gotmsg.HostInfoLength,tmpnr.nr_item+22,2);
								memcpy(&statusRespToBeProcessed.HostPort,&(itemFromQueue.dataBuf[22]),2);
								
								memcpy(&statusRespToBeProcessed.Hostname,&(itemFromQueue.dataBuf[24]),(statusRespToBeProcessed.HostInfoLength-2));
								
								int length=(itemFromQueue.msgHeader.msgDataLength)-(strlen(statusRespToBeProcessed.Hostname)+20+2+2);
								int readLen=(strlen(statusRespToBeProcessed.Hostname)+20+2+2);
								int it=length/19;
								
								if(lastStatusType==1)
								{
									//statusRespMap
									list<int> tempPortListToInsertInMap;
									for(int k=0;k<it;k++)
									{
											memcpy(&statusRespToBeProcessed.RecordLength[k],&(itemFromQueue.dataBuf[readLen+(k*19)]),4);
											uint16_t temp=0;
											
											memcpy(&temp,&(itemFromQueue.dataBuf[readLen+4+(k*19)]),2);
											//printf("READLEN: %x and READLEN+1 is %x\n",(itemFromQueue.dataBuf[readLen+4+(k*19)]),(itemFromQueue.dataBuf[readLen+5+(k*19)]));
											int portValueForList= temp;
											tempPortListToInsertInMap.push_back(portValueForList);
											//printf("Port %d pushed in list for mapkey %d\n",portValueForList,statusRespToBeProcessed.HostPort);
									}
									pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
										statusRespMap.insert(pair<int,list<int> >((int)statusRespToBeProcessed.HostPort,tempPortListToInsertInMap));
									}
									pthread_mutex_unlock(&cntrlCFlagMutex);
								}
								else if(lastStatusType==2)
								{
										//TODO: Write the response recieved to the output file.
							//		printf("Ready to write the STATUS RESP receieved\n");
									
							//		int portNumRecieved;
							//		int len;
									/*
									memcpy(&len,&(itemFromQueue.dataBuf[20]),2);
									memcpy(&portNumRecieved,&(itemFromQueue.dataBuf[22]),2);
									printf("code is here----1---------\n");
									char hostNameRecieved[512];
									memset(hostNameRecieved,'\0',512);
									printf("Length is %d\n\n",len);
									memcpy(hostNameRecieved,&(itemFromQueue.dataBuf[24]),len-2);
									printf("code is here----2---------\n");*/
									int recordLength=0;
									//memcpy(&recordLength,itemFromQueue.dataBuf+(22+len),4);
									memcpy(&recordLength,&(itemFromQueue.dataBuf[readLen]),4);
							//		printf("code is here----3---------\n");
									char statusFileWriteBuf[8192];
									memset(&statusFileWriteBuf[0],'\0',8192);
							//		printf("");
									memcpy(&statusFileWriteBuf[0],&(itemFromQueue.dataBuf[readLen+4]),recordLength);
								//	printf("Record Length is %d\n",recordLength);
								//	printf("code is here----4---------\n");

								pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
										pthread_mutex_lock(&statusFileWriteLock);
										FILE *statusOutfile = fopen(statusFileName,"a+");
										
										int numberOfLines=0;
										int k = 0;
										while(statusFileWriteBuf[k] != '\0')
										{
											k++;
											if(statusFileWriteBuf[k]=='\n')
											{
												numberOfLines++;
											}
										}
										
								//	printf("code is here----5---------\n");
										int numberOfFiles= numberOfLines/7;
								//		printf("Number of lines is %d",numberOfLines);
										if(numberOfFiles == 0)
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has no file\n",statusRespToBeProcessed.HostPort);
										}
										else if (numberOfFiles == 1)
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has the following file\n",statusRespToBeProcessed.HostPort);
										}
										else
										{
											fprintf(statusOutfile,"nunki.usc.edu:%d has the following files\n",statusRespToBeProcessed.HostPort);
										}
								//		printf("Size of statuswritebuffer is %d\n",(int)strlen(statusFileWriteBuf));
										fprintf(statusOutfile,"%s",statusFileWriteBuf);
										fclose(statusOutfile);
										pthread_mutex_unlock(&statusFileWriteLock);
										}
									pthread_mutex_unlock(&cntrlCFlagMutex);
									
									
								//	printf("Status File Output written for status resp recieved from %d.\n",statusRespToBeProcessed.HostPort);
								}
								else
								{
									//printf("Invalid lastStatusType detected.\n");
								}
							}
							else
							{

								pthread_mutex_lock(&sockIndexMapMutex);
								 index=sockFDToQIndexMap[tmp.sockOfMsgReciept];
								 pthread_mutex_lock(&wrtieQMutex[index]);
										////printf("EVENT DISPATCHER: JOIN RESP msgtype %x and buffer is %s",msgToBePushed.msgHeader,);
										wrtieThreadQueue[index].push_back(itemFromQueue);
										//printf("EVENT DISPATCHER: STATUS RESP: Msg pushed to writeQueue of %d\n",index);
										pthread_cond_broadcast(&wrtieQCV[index]);

								pthread_mutex_unlock(&wrtieQMutex[index]);	
							pthread_mutex_unlock(&sockIndexMapMutex);


								
							
				pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==tmp.sockOfMsgReciept)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "f  %s %s:%hu STRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);



							}
							



						}





				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:STATUS RESPONSE The msg already exists in the map.DO NOT FORWARD!!!!\n");
					//exit(0);
					continue;  //Think abt this. Whether to put continue or exit(0);
				}

			

			}//END OF STATUS RESPONSE MSG
			else if(itemFromQueue.msgHeader.messageType==0xF6) //If CHECK message
			{
					//printf("CHECK Msg Detected.\n");
				/*
					check if i am beacon node or not?
						if beacon
							then stop flooding and send response
						else continue flooding

				*/
				
				if(itemFromQueue.sockfd!=-1)
				{
					
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "r %s %s:%hu CKRQ 27 0x%02x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											//(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19]);
										pthread_mutex_unlock(&logFileMutex);
				}














				
				//code for beacon node here.	
				if(!iAmBeacon)
				{
					//Code to process a msg from queue if it is a CHECK Msg.
					//printf("EVENT DISPATCHER: CHECK MESSAGE detected.\n");
					
					map<string,msgLifeTimeClass>::iterator uoidIteratorCheckMsg;
					string str ((const char*)itemFromQueue.msgHeader.UOID,20);
					pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
					uoidIteratorCheckMsg=UOIDMsgLifeTimeMap.find(str);

					if(uoidIteratorCheckMsg == UOIDMsgLifeTimeMap.end())
					{

							unsigned char uoidToInsertInMap[20];
							memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
							string uoid ((const char*)uoidToInsertInMap,20);
							msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
							//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
							//newEntry.msgLifeTimeValue=msgLifeTime;
							UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);						
	
							//Make a new item to be pushed on all queues.
							//printf("---------------1--------------\n");
							
							msgToBePushed.sockfd=itemFromQueue.sockfd;
							//populate the header as the same only changing the TTL value.
							msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
							memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
							//Decrease TTL by 1 is ttl in header less than node ttl
							//else set node ttl as the new ttl ..
							if((itemFromQueue.msgHeader.ttlInHeader-1)<ttl)
							{
								msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
							}
							else
							{
								msgToBePushed.msgHeader.ttlInHeader=ttl;	
							}

							msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
							//Copy Data from itemfromqueue into new quueue item.
							//memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
							//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
							//forward the msg to other nodes if the new ttl>0
							if(msgToBePushed.msgHeader.ttlInHeader!=0)
							{
								//Find index of writeQueue from map for all entries in connectedNodeList
								map<string,int>::iterator conNodeListIteratorCheck;
								//printf("---------------2--------------\n");
								pthread_mutex_lock(&connectedNodeListMutex);
								//printf("---------------4--------------\n");
								for ( conNodeListIteratorCheck=connectedNodeList.begin() ; conNodeListIteratorCheck != connectedNodeList.end(); conNodeListIteratorCheck++ )
								{

									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

									//printf("---------------5--------------\n");
									int socket=(*conNodeListIteratorCheck).second;
									//printf("---------------5--------------%d\n",socket);
									if(socket!=itemFromQueue.sockfd)
									{
										//printf("---------------6--------------\n");
										pthread_mutex_lock(&sockIndexMapMutex);
										int index=sockFDToQIndexMap[socket];
											pthread_mutex_lock(&wrtieQMutex[index]);
											//	printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
												wrtieThreadQueue[index].push_back(msgToBePushed);
												//printf("EVENT DISPATCHER: CHECK MSG: Msg pushed to writeQueue of %d\n",index);
												pthread_cond_broadcast(&wrtieQCV[index]);

											pthread_mutex_unlock(&wrtieQMutex[index]);								
										pthread_mutex_unlock(&sockIndexMapMutex);
											
											//char* str1 = (char*)((*conNodeListIteratorCheck).first).c_str();	
											char* str1 = (char*) malloc(512); 
											memset(&str1[0],'\0',512);
											memcpy(&str1[0],&(((*conNodeListIteratorCheck).first).c_str()[0]),19);

											char *str=(char*)malloc(512);
											memset(str,'\0',512);
											memcpy(&str[0],&str1[0],strlen(str1));
										//printf("String from list is %s\n",str);
										
										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										
										portTemp=atoi(tempPort);
										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "f  %s %s:%hu CKRQ %d 0x%02x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(msgToBePushed.msgHeader.msgDataLength+27),
											(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
											(unsigned char)msgToBePushed.msgHeader.UOID[16],
											(unsigned char)msgToBePushed.msgHeader.UOID[17],
											(unsigned char)msgToBePushed.msgHeader.UOID[18],
											(unsigned char)msgToBePushed.msgHeader.UOID[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);










									}
									//printf("---------------7--------------\n");
								}
								pthread_mutex_unlock(&connectedNodeListMutex);
							}
					}
					else
					{
						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
						//printf("EVENT DISPATCHER:CHECK REQUEST The msg already exists in the map.DO NOT FORWARD!!!!\n");
						continue;
					}
				}
				else
				{
					//Now populate the CheckResponse msg and push it to the queue..
					if(itemFromQueue.sockfd!=-1)
					{
								
						queueItem checkResp;
						
						checkResp.sockfd=itemFromQueue.sockfd;

						checkResp.msgHeader.messageType=0xF5;
						unsigned char *buff1;
						char* msg = (char*)"CKRS";

						//printf("NodeID is %s\n",nodeInstanceId);
			
						buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
						memcpy(checkResp.msgHeader.UOID,buf,20);
						
						checkResp.msgHeader.ttlInHeader=ttl;	
						checkResp.msgHeader.msgDataLength=20;
						
						//Populate the checkRespDataBuf.
						
						//checkMsgDataClass checkRespData;
						char *checkRespDataBuf=new char[512];
						//memset(joinRespDataBuf,'-',512);
						
						memcpy(&checkRespDataBuf[0],itemFromQueue.msgHeader.UOID,20);
						
						//printf("Buffer is: [%s]\n",joinRespDataBuf);

						//printf("NEW VALUE: %lu",computedDist1);
						//memcpy(&joinRespDataBuf[20],(void*)htonl("200"),sizeof(uint32_t));
						//printf("\n[%X,%X,%X,%X,%X,%c]\n",joinRespDataBuf[19],joinRespDataBuf[20],joinRespDataBuf[21],joinRespDataBuf[22],joinRespDataBuf[23],joinRespDataBuf[38]);
						//printf("Size of the buffer is %d",(int)strlen(joinRespDataBuf));
						//copy temp buf to queueitem databuf
						memcpy(&checkResp.dataBuf[0],checkRespDataBuf,checkResp.msgHeader.msgDataLength);
						
						delete[] checkRespDataBuf;
						//Push the item in proper write Queue.
						pthread_mutex_lock(&sockIndexMapMutex);
						int index=sockFDToQIndexMap[itemFromQueue.sockfd];
							pthread_mutex_lock(&wrtieQMutex[index]);
								wrtieThreadQueue[index].push_back(checkResp);
								//printf("EVENT DISPATCHER: CHECK RESPONSE MSG: Msg pushed to writeQueue of %d\n",index);
								pthread_cond_broadcast(&wrtieQCV[index]);

							pthread_mutex_unlock(&wrtieQMutex[index]);								
						pthread_mutex_unlock(&sockIndexMapMutex);
						
												
						
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "s %s %s:%hu CKRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(checkResp.msgHeader.msgDataLength+27),
											(unsigned char)checkResp.msgHeader.ttlInHeader,
											(unsigned char)checkResp.msgHeader.UOID[16],
											(unsigned char)checkResp.msgHeader.UOID[17],
											(unsigned char)checkResp.msgHeader.UOID[18],
											(unsigned char)checkResp.msgHeader.UOID[19],
											(unsigned char)checkResp.dataBuf[16],
											(unsigned char)checkResp.dataBuf[17],
											(unsigned char)checkResp.dataBuf[18],
											(unsigned char)checkResp.dataBuf[19]);
										pthread_mutex_unlock(&logFileMutex);

						




						//printf("---------------3--------------\n");
						

					
					}
				}
			}//end of CHECK MSG.
			else if(itemFromQueue.msgHeader.messageType==0xF5) //If CHECK RESPONSE
			{
				
				
				//char errorCode= '\0';
				//memcpy(&errorCode,&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
				//printf("EVENT DISPATCHER: CHECK RESP \n");
				//close the connection with that node.
				//flood check message to the network.

				/*
					IF check response
					find the index of corresponding UOID from the UOIDmap and put the response to the particular write thread 
						
				*/

												
						
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "r %s %s:%hu CKRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
										pthread_mutex_unlock(&logFileMutex);
				















				//printf("EVENT DISPATCHER: CHECK RESPONSE msg detected.\n");
				
				map<string,msgLifeTimeClass>::iterator uoidIteratorCheck;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);
				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIteratorCheck=UOIDMsgLifeTimeMap.find(str);
				if(uoidIteratorCheck == UOIDMsgLifeTimeMap.end())
				{	

						//Entry not found in the map.. make a new entry in the map for it. and continue to process the msg.
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string, msgLifeTimeClass>(uoid, newEntry));
						

						unsigned char uoidFromItemData[20];
						memcpy(&uoidFromItemData[0],&(itemFromQueue.dataBuf[0]),20);
						string str1((const char*)uoidFromItemData,20);
						uoidIteratorCheck=UOIDMsgLifeTimeMap.find(str1);

						if(uoidIteratorCheck==UOIDMsgLifeTimeMap.end())
						{
						
							//NOT FOUND
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							//printf("EVENT DISPATCHER: CHECK RESPONSE. THERE HAS NOT BEEN ANY CHECK MESSAGE FOR THIS UOID.\n\n");
						
						}
						else
						{
							//Found in the UOID MAP.
							int index=-1;

							msgLifeTimeClass tmp=(*uoidIteratorCheck).second;
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							if(tmp.sockOfMsgReciept!=-1)
							{
								//msgLifeTimeClass tmp=(*uoidIteratorCheck).second;
								pthread_mutex_lock(&sockIndexMapMutex);
									 index=sockFDToQIndexMap[tmp.sockOfMsgReciept];
									 pthread_mutex_lock(&wrtieQMutex[index]);
											//printf("EVENT DISPATCHER: JOIN RESP msgtype %x and buffer is %s",msgToBePushed.msgHeader,);
											wrtieThreadQueue[index].push_back(itemFromQueue);
											//printf("EVENT DISPATCHER: CHECK RESP: Msg pushed to writeQueue of %d\n",index);
											pthread_cond_broadcast(&wrtieQCV[index]);

									pthread_mutex_unlock(&wrtieQMutex[index]);	
								pthread_mutex_unlock(&sockIndexMapMutex);

												
						
					pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==tmp.sockOfMsgReciept)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
						pthread_mutex_unlock(&connectedNodeListMutex);

										pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "f %s %s:%hu CKRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
										pthread_mutex_unlock(&logFileMutex);
				

							}
							else
							{
								pthread_mutex_lock(&checkTimeoutMutex);
								checkFlagReceived=true;
								pthread_mutex_unlock(&checkTimeoutMutex);
							}

						}
				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:CHECK RESPONSE -> msg already exists in the map.DO NOT FORWARD!!!!\n");
					//exit(0);
					continue;  //Think abt this. Whether to put continue or exit(0);
				}


				
				
			}//End of CHECK RESPONSE MSG.
			else if(itemFromQueue.msgHeader.messageType==0xEC)       //SEARCH REQ MSG
			{
				//printf("\n-------------SEARCH MSG-----------------\n");
				//printf("\n0X%02X\n",itemFromQueue.msgHeader.messageType);
				if(itemFromQueue.sockfd!=-1)
				{
					
						//logging SHRQ into file.
						pthread_mutex_lock(&connectedNodeListMutex);
							uint16_t portTemp=0;
							char *tempHost=(char*)malloc(512);
							map<string,int>::iterator it;
						for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
						{
							//printf("\n------->%d<-----%d----\n",(*it).second,itemFromQueue.sockfd);
							if((*it).second==itemFromQueue.sockfd)
							{
										char* str1 = (char*) malloc(512); 
										memset(&str1[0],'\0',512);
										memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

										char *str=(char*)malloc(512);
										memset(str,'\0',512);
										memcpy(&str[0],&str1[0],strlen(str1));
							//			printf("String from list is %s\n",str);
										
										tempHost=strtok(str,"_");
							//			printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
							//			printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										
										portTemp=atoi(tempPort);
										break;
							}
						
						}
						pthread_mutex_unlock(&connectedNodeListMutex);



						pthread_mutex_lock(&logFileMutex);
							char searchType[256];
							memset(&searchType[0],'\0',256);
							if(itemFromQueue.dataBuf[0]==0x01)
							{
								strncpy(&searchType[0],"filename",strlen("filename"));
							}
							else if(itemFromQueue.dataBuf[0]==0x02)
							{
								strncpy(&searchType[0],"sha1hash",strlen("sha1hash"));
							}
							else if(itemFromQueue.dataBuf[0]==0x03)
							{
								strncpy(&searchType[0],"keywords",strlen("keywords"));
							}
							/*else
							{
								strncpy(&searchType[0],"Invalid Search Type",strlen("Invalid Search Type"));
							}*/
							
							char query[8000];
							memset(&query[0],'\0',8000);
							int queryLength = itemFromQueue.msgHeader.msgDataLength-1;
							strncpy(&query[0],&itemFromQueue.dataBuf[1],queryLength);

							gettimeofday(&tv, NULL); 
							int sec = tv.tv_sec ;
							int msec = tv.tv_usec/1000;
							char *time = (char *)malloc(14);
							memset(time,0,14);
							sprintf(time,"%10ld.%03d",(long)sec,msec);
							time[strlen(time)]='\0';
							fprintf(logFilePtr, "r  %s %s:%hu SHRQ %d 0x%02x %x%x%x%x %s %s\n",time,
									tempHost, portTemp,
									(itemFromQueue.msgHeader.msgDataLength+27),
									(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
									(unsigned char)itemFromQueue.msgHeader.UOID[16],
									(unsigned char)itemFromQueue.msgHeader.UOID[17],
									(unsigned char)itemFromQueue.msgHeader.UOID[18],
									(unsigned char)itemFromQueue.msgHeader.UOID[19],
									searchType,query);
							pthread_mutex_unlock(&logFileMutex);


				}
				//printf("------------------2-------------------------\n");
						//printUOID((unsigned char*)str.c_str());
						//map<string,msgLifeTimeClass>::iterator uoidIterator9;
						//printf("UOID MAP is :");
						//for(uoidIterator9=UOIDMsgLifeTimeMap.begin();uoidIterator9!=UOIDMsgLifeTimeMap.end();uoidIterator9++)
						//{
							//printUOID( (unsigned char*)((*uoidIterator9).first).c_str());
					//	}

				
				
				
				
				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);

				uoidIterator=UOIDMsgLifeTimeMap.find(str);
						
				
				
				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));

						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
								

						msgToBePushed.sockfd=itemFromQueue.sockfd;
						//populate the header as the same only changing the TTL value.
						msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
						memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
						//Decrease TTL by 1 is ttl in header less than node ttl
						//else set node ttl as the new ttl ..
						//printf("---------------%d-----char %c--%x-------\n",itemFromQueue.msgHeader.ttlInHeader,itemFromQueue.msgHeader.ttlInHeader-1,  itemFromQueue.msgHeader.ttlInHeader);
						//printf("------------------3-------------------------\n");
						if(itemFromQueue.sockfd!=-1)
						{
							if((itemFromQueue.msgHeader.ttlInHeader-1)<(char)ttl)
							{
								//printf("code is here.\n");
								msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
							}
							else
							{
								//printf("WTF\n");
								msgToBePushed.msgHeader.ttlInHeader=ttl;	
							}
						}
						else
						{
							msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader;
						}
						//printf("------------------4-------------------------\n");
						msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
						//Copy Data from itemfromqueue into new quueue item.
						memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
						//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
						//forward the msg to other nodes if the new ttl>0
						
						if(msgToBePushed.msgHeader.ttlInHeader>0)
						{
							//printf("------------------5-------------------------\n");
							
							//Find index of writeQueue from map for all entries in connectedNodeList
							map<string,int>::iterator conNodeListIterator2;
							//printf("---------------2--------------\n");
							pthread_mutex_lock(&connectedNodeListMutex);
							//printf("---------------4--------------\n");
							for ( conNodeListIterator2=connectedNodeList.begin() ; conNodeListIterator2 != connectedNodeList.end(); conNodeListIterator2++ )
							{

								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								//printf("---------------5--------------\n");
								int socket=(*conNodeListIterator2).second;
								//printf("---------------5--------------%d\n",socket);
								if(socket!=itemFromQueue.sockfd)
								{
									//printf("---------------6--------------\n");
									pthread_mutex_lock(&sockIndexMapMutex);
									int index=sockFDToQIndexMap[socket];
										pthread_mutex_lock(&wrtieQMutex[index]);
										//	printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
											wrtieThreadQueue[index].push_back(msgToBePushed);
											//printf("EVENT DISPATCHER: STATUS REQ MSG: Msg pushed to writeQueue of %d\n",index);
											pthread_cond_broadcast(&wrtieQCV[index]);

										pthread_mutex_unlock(&wrtieQMutex[index]);								
									pthread_mutex_unlock(&sockIndexMapMutex);



									//log for flooding SHRQ.

											
										char* str1 = (char*) malloc(512); 
										memset(&str1[0],'\0',512);
										memcpy(&str1[0],&(((*conNodeListIterator2).first).c_str()[0]),19);

										char *str=(char*)malloc(512);
										memset(str,'\0',512);
										memcpy(&str[0],&str1[0],strlen(str1));

										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										
										portTemp=atoi(tempPort);

										pthread_mutex_lock(&logFileMutex);
											char searchType[256];
											memset(&searchType[0],'\0',256);
											if(msgToBePushed.dataBuf[0]==0x01)
											{
												strncpy(&searchType[0],"filename",strlen("filename"));
											}
											else if(msgToBePushed.dataBuf[0]==0x02)
											{
												strncpy(&searchType[0],"sha1hash",strlen("sha1hash"));
											}
											else if(msgToBePushed.dataBuf[0]==0x03)
											{
												strncpy(&searchType[0],"keywords",strlen("keywords"));
											}
										/*	else
											{
												strncpy(&searchType[0],"Invalid Search Type",strlen("Invalid Search Type"));
											}
										*/	
											char query[8000];
											memset(&query[0],'\0',8000);
											int queryLength = msgToBePushed.msgHeader.msgDataLength-1;
											strncpy(&query[0],&msgToBePushed.dataBuf[1],queryLength);

											gettimeofday(&tv, NULL); 
											int sec = tv.tv_sec ;
											int msec = tv.tv_usec/1000;
											char *time = (char *)malloc(14);
											memset(time,0,14);
											sprintf(time,"%10ld.%03d",(long)sec,msec);
											time[strlen(time)]='\0';
											fprintf(logFilePtr, "f %s %s:%hu SHRQ %d 0x%02x %x%x%x%x %s %s\n",time,
														tempHost,
														portTemp,
														(msgToBePushed.msgHeader.msgDataLength+27),
														(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
														(unsigned char)msgToBePushed.msgHeader.UOID[16],
														(unsigned char)msgToBePushed.msgHeader.UOID[17],
														(unsigned char)msgToBePushed.msgHeader.UOID[18],
														(unsigned char)msgToBePushed.msgHeader.UOID[19],
														searchType,query);
											pthread_mutex_unlock(&logFileMutex);

								}
								//printf("---------------7--------------\n");
							}
							pthread_mutex_unlock(&connectedNodeListMutex);
							//printf("------------------6-------------------------\n");
						}


						if(itemFromQueue.sockfd==-1)
						{
							//The eventdispatcher that poped the msg is at the same node as the terminal where status msg was requested.
							// So add the list of neighbors for the current node the the datalist that will be written into the NAM file.
							//printf("I am where status req started.\n");
							if(itemFromQueue.dataBuf[0]==0x01)
							{
						//		printf("EVENT DISPATCHER: Sending Search response for file : %s\n",(itemFromQueue.dataBuf+1));
								char tempFileName[255];
								memset(tempFileName,'\0',255);
								memcpy(&tempFileName[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
								char fileName[256];
								memset(fileName,'\0',256);
								for(int i = 0; tempFileName[i]; i++)
									fileName[ i ] = tolower(tempFileName[i]);
						//		printf("EVENT DISPATCHER: File is : %s\n",fileName);
								pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
								pthread_mutex_lock(&indexMutex);
								//compare filename value after converting into lower case
								list<indexFileMetaInfo>::iterator it1;
								for(it1 = indexFileMetaInfoList.begin(); it1 != indexFileMetaInfoList.end(); it1++)
								{
									char str[256];
									memset(str,'\0',256);
									for(int i = 0; (*it1).originalFileName[i]; i++)
										str[ i ] = tolower((*it1).originalFileName[i]);
									//char str[] = toupper((*it1).originalFileName);
									//printf("List fileName is : %s\n",str);
									if(strcmp(fileName,str)==0)
									{
										//printf("File found at origin.\n");
										searchResponseInfo insertSearchResponseMap;
										insertSearchResponseMap.isOrigin = true;
										map<int,string>::iterator it2;
										int numFileId = (*it1).numFileName;
										it2 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it2).second.c_str();
								//		printf("File found at origin with index : %d. and fileid is :\n",numFileId);
										memcpy(&insertSearchResponseMap.fileID[0],&tempFileID[0],strlen(tempFileID));
										memcpy(&insertSearchResponseMap.originalFileName[0],&str[0],strlen(str));
										
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(insertSearchResponseMap.fileMetaBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											////printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
								//		printf("Length of insertSearchResponseMap.fileMetaBuffer is %d\n",strlen(insertSearchResponseMap.fileMetaBuffer));
										fclose(temp);	

										indexSearchResponseMap.insert(pair<int,searchResponseInfo>(searchIndex,insertSearchResponseMap));
										//printUOID((unsigned char *)(*it2).second.c_str());
										

										searchIndex++;
									}
								}
								pthread_mutex_unlock(&indexMutex);
									}
								pthread_mutex_unlock(&cntrlCFlagMutex);
									
									

							}
							else if (itemFromQueue.dataBuf[0]==0x02)
							{
								//TODO: Write the status file data for the req initiating node.
						//		printf("EVENT DISPATCHER: Sending Search response for sha1 : %s\n",(itemFromQueue.dataBuf+1));
								char sha1[41];
								memset(sha1,'\0',255);
								memcpy(&sha1[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
						//		printf("EVENT DISPATCHER: SHA1 is : %s\n",sha1);
								//compare sha1 values after converting into lower case
								pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
								pthread_mutex_lock(&indexMutex);
								multimap<string,int>::iterator it2;
								for(it2=indexSHA1Map.begin();it2!=indexSHA1Map.end();it2++)
								{		
									//it2 = indexSHA1Map.find(sha1);
									if(strcmp((const char*)(*it2).first.c_str(),sha1)==0)
									{
								//	printf("SHA1 found in the map.\n");
									//printf("File found at origin.\n");
										searchResponseInfo insertSearchResponseMap;
										insertSearchResponseMap.isOrigin = true;
										int numFileId = (*it2).second;
										map<int,string>::iterator it3;
										it3 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it3).second.c_str();
									//	printf("File found at origin with index : %d. and fileid is :\n",numFileId);
										memcpy(&insertSearchResponseMap.fileID[0],&tempFileID[0],strlen(tempFileID));
			
										list<indexFileMetaInfo>::iterator it4;
										for(it4 = indexFileMetaInfoList.begin(); it4 != indexFileMetaInfoList.end(); it4++)
										{
											if((*it4).numFileName==numFileId)
											{
												memcpy(&insertSearchResponseMap.originalFileName[0],&((*it4).originalFileName[0]),strlen((*it4).originalFileName));
												break;
											}

										}
										
										
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(insertSearchResponseMap.fileMetaBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
								//		printf("Length of insertSearchResponseMap.fileMetaBuffer is %d\n",strlen(insertSearchResponseMap.fileMetaBuffer));
										fclose(temp);	

										indexSearchResponseMap.insert(pair<int,searchResponseInfo>(searchIndex,insertSearchResponseMap));
										//printUOID((unsigned char *)(*it2).second.c_str());
										searchIndex++;

									}
								}
								pthread_mutex_unlock(&indexMutex);
									}
									pthread_mutex_unlock(&cntrlCFlagMutex);
									
									

							}
							else if (itemFromQueue.dataBuf[0]==0x03)
							{
							//	printf("EVENT DISPATCHER: Sending Search response for keywords : %s\n",(itemFromQueue.dataBuf+1));
								char keywords[8192];
								memset(keywords,'\0',8192);
								memcpy(&keywords[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
							//	printf("EVENT DISPATCHER: Keywords are : %s\n",keywords);
								
								//---------------------------------------------------------
								//create bitvector from given keyword.
								//---------------------------------------------------------
									/*printf("Bit Vector is:\n\n");
										for(int k=0;k<128;k++)
										{
											printf("%x",searchFileBitVector[k]);
										}
										printf("\n");
									*/
									char *result = NULL;
									result = strtok( keywords, " ");
									unsigned char searchFileBitVector[128];
									memset(&searchFileBitVector[0],0x00,128);
										while( result != NULL )
										{
											//printf( "result is \"%s\" with length %d\n", result,strlen(result) );
											
											char key[512];
											memset(key, '\0',512);
											memcpy(&key[0],&result[0],strlen(result));

											unsigned char sha[20];	//20 bytes
											unsigned char md5[16];	//16 bytes

											int sha1Index;
											int md5Index;

											

											
											MD5_CTX c;
											MD5_Init(&c);
											int len = strlen(key);
											MD5_Update(&c,(void *)key,len);
											
											
											MD5_Final(&md5[0], &c);
											//printf("Calculated MD5: ");
											//	for(unsigned int i=0; i<16;i++)
											//	{
											//		printf("%x",md5[i]);
											//	}
											//	printf("\n");

											/*MD5((unsigned char*)key,len,md5);
											printf("Calculated MD5: ");
												for(unsigned int i=0; i<17;i++)
												{
													printf("%x",md5[i]);
												}
												printf("\n");
											*/


											if ((0x01 & md5[14]) != 0x00)
											{
												md5Index = 256+ (unsigned int)md5[15];
											//		printf("md5Index : %d and md5[15]= %d, %02x\n", md5Index, md5[15], md5[15]);
												
											}
											else{
												md5Index = (unsigned int)md5[15];
												
											//		printf("md5Index : %d\n", md5Index);
												
											}

											
											SHA_CTX c1;
											SHA1_Init(&c1);
											SHA1_Update(&c1,(void *)key,len);
											SHA1_Final(&sha[0], &c1);
											//printf("Calculated SHA1: ");
											//	for(unsigned int i=0; i<20;i++)
											//	{
											//		printf("%x",sha[i]);
											//	}
											//	printf("\n");
											if ((0x01 & sha[18]) != 0x00)
											{
												sha1Index = 256+ (unsigned int)sha[19] +512;
										//			printf("sha1Index : %d and sha[19]= %d, %02x\n", sha1Index, sha[19], sha[19]);
												
											}
											else{
												sha1Index = (unsigned int)sha[19]+512;
												
										//			printf("sha1Index : %d\n", sha1Index);
												
											}

										//	printf("\nBITVECTOR indexes: %d --> %d\n",sha1Index,md5Index);
											if(md5Index<1024)
											{
												//md5Index=0;
												int bitVectorIndex=127- ceil(md5Index/8) ;
												int rem= ((md5Index)%8);
												searchFileBitVector[bitVectorIndex]=searchFileBitVector[bitVectorIndex] | ((unsigned int)1 << rem);
										//		printf("bitIndexis %d rem is %d\n",bitVectorIndex,rem);
											}
											if(sha1Index<1024)
											{
												//sha1Index=8;
												int bitVectorIndex=127- ceil(sha1Index/8);
												int rem= ((sha1Index)%8);
												searchFileBitVector[bitVectorIndex]=searchFileBitVector[bitVectorIndex] | ((unsigned int)1 << rem);
										//		printf("bitIndexis %d rem is %d\n",bitVectorIndex,rem);
											}
										/**	printf("Bit Vector is:\n\n");
											for(int k=0;k<128;k++)
											{
												printf("%x",searchFileBitVector[k]);
											}
											printf("\n");
											*/
											result = strtok( NULL, " " );
										}
										char formattedBitVector[257];
										memset(&formattedBitVector[0],'\0',257);
										for (int i =0 ;i< 128 ;i++)
										{
											unsigned char change[3] = {0};
											sprintf((char*)change, "%2.2x", searchFileBitVector[i]);
											sprintf((char*)formattedBitVector+2*i,"%s",change);
										}
								//		printf("%s\n",formattedBitVector);
								//		printf("##########################################\n");


								//----------------------------------------------------------
								//iterate over bitVector list and compare both bitVectors
								//----------------------------------------------------------
								pthread_mutex_lock(&cntrlCFlagMutex);
								if(!cntrlCFlag)
									{
								pthread_mutex_lock(&indexMutex);
								list<bitVectorIndexItem>::iterator it5;
								char compareBitVector[257];
								bool matchBitVectorFlag = true;
								for(it5 = indexBitVectoreList.begin(); it5!=indexBitVectoreList.end();it5++)
								{
									matchBitVectorFlag = true;
									memcpy(&compareBitVector[0],&((*it5).indexBitVector[0]),strlen((*it5).indexBitVector));
								//	printf("%s\n",compareBitVector);
								//	printf("---------------------------------------\n");
									for(int k=0;k<(int)strlen(compareBitVector);k++)
									{
										int formatedIntValue = charHexLookupConverter(formattedBitVector[k]);
										int compareIntValue = charHexLookupConverter(compareBitVector[k]);
										//printf("Int value is [%d  %d]\n", a,b);

										if ((formatedIntValue & compareIntValue) != formatedIntValue)
										{
											//printf("AND fail\n");
											matchBitVectorFlag = false;
											break;
										}
										//printf("k = %d ----> [%d]--------[%d]\n",k,a,b);
									}
									if(matchBitVectorFlag == true)
									{
										char str[256];
										memset(str,'\0',256);
									//	printf("Both bitvectors matched...\n");
										searchResponseInfo insertSearchResponseMap;
										insertSearchResponseMap.isOrigin = true;
										map<int,string>::iterator it6;
										int numFileId = (*it5).numFileName;
										it6 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it6).second.c_str();
										
										
										memcpy(&insertSearchResponseMap.fileID[0],&tempFileID[0],strlen(tempFileID));
										//printUOID(insertSearchResponseMap.fileID);
										list<indexFileMetaInfo>::iterator it7;
										for(it7 = indexFileMetaInfoList.begin(); it7 != indexFileMetaInfoList.end(); it7++)
										{
											if((*it7).numFileName==numFileId)
											{
												memcpy(&insertSearchResponseMap.originalFileName[0],&((*it7).originalFileName[0]),strlen((*it7).originalFileName));
												break;
											}

										}
										//memcpy(&insertSearchResponseMap.originalFileName[0],&str[0],strlen(str));
									//	printf("File found at origin with index : %d. and fileName is : %s\n",numFileId,insertSearchResponseMap.originalFileName);
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(insertSearchResponseMap.fileMetaBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
										//printf("Length of insertSearchResponseMap.fileMetaBuffer is %d\n",strlen(insertSearchResponseMap.fileMetaBuffer));
										fclose(temp);	

										indexSearchResponseMap.insert(pair<int,searchResponseInfo>(searchIndex,insertSearchResponseMap));
										//printUOID((unsigned char *)(*it2).second.c_str());
										searchIndex++;
									}
									else
									{
								//		printf("\nNot matched...\n");
									}

								}
								pthread_mutex_unlock(&indexMutex);
									}
								pthread_mutex_unlock(&cntrlCFlagMutex);
								
									

							}
							else
							{
								//printf("Wrong message type detected on Search req packet..\n");
							}

							/*	pthread_mutex_lock(&indexMutex);
								map<int,searchResponseInfo>::iterator it8;
								for(it8 = indexSearchResponseMap.begin(); it8!=indexSearchResponseMap.end();it8++)
								{
									printf("Here.... %d ---> %s and isOrigin flag : \n",(*it8).first,(*it8).second.originalFileName);
									cout<<(*it8).second.isOrigin<<endl;
									printf("\nFile id is : \n");
									printUOID((*it8).second.fileID);
								}
								pthread_mutex_unlock(&indexMutex);*/

							/*	
								pthread_mutex_lock(&indexMutex);
								printf("#######################################################\n");
								printf("\nMap Size is : %d\n",indexSearchResponseMap.size());
								map<int,searchResponseInfo>::iterator displayIterator;
								for(displayIterator = indexSearchResponseMap.begin(); displayIterator != indexSearchResponseMap.end(); displayIterator++)
								{
									printf("File ID  is:\n");
									printUOID((*displayIterator).second.fileID);
									printf("Original File Name is : %s\n",(*displayIterator).second.originalFileName);
									cout<<"Am i origin: "<<(*displayIterator).second.isOrigin<<endl;
									printf("File Meta Buffer is : %s\n",(*displayIterator).second.fileMetaBuffer);
								}
								printf("#######################################################\n");

								pthread_mutex_unlock(&indexMutex);*/


						}
						else// the search req recieved is from some other node.. so send him the status response packet.
						{
						//	printf("\nEVENT DISPATCHER: search req recieved is from some other node...\n");
							queueItem searchRespToBePushed;
							searchRespToBePushed.sockfd=itemFromQueue.sockfd;
							searchRespToBePushed.msgHeader.messageType=0xEB;
							unsigned char *buff1;
							char* msg = (char*)"SHRS";
							int datalength= 0;
							buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
							memcpy(&(searchRespToBePushed.msgHeader.UOID[0]),&buf[0],20);

							searchRespToBePushed.msgHeader.ttlInHeader=ttl;
							
							
							char respBuf[8192];
							memset(&(respBuf[0]),'\0',8192);

							memcpy(&(respBuf[0]),&(itemFromQueue.msgHeader.UOID),20);
							datalength += 20;
							
						//	int tempdatalength=0;
							int numFileId = 0;
							map<int,bool> cacheFileNumber;
							if(itemFromQueue.dataBuf[0]==0x01)
							{
							//	printf("EVENT DISPATCHER: Sending Search response for file : %s\n",(itemFromQueue.dataBuf+1));
								char tempFileName[255];
								memset(tempFileName,'\0',255);
								memcpy(&tempFileName[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
								char fileName[256];
								memset(fileName,'\0',256);
								for(int i = 0; tempFileName[i]; i++)
									fileName[ i ] = tolower(tempFileName[i]);
							//	printf("EVENT DISPATCHER: File is : %s\n",fileName);
								pthread_mutex_lock(&indexMutex);
								//compare filename value after converting into lower case
								list<indexFileMetaInfo>::iterator it1;
								for(it1 = indexFileMetaInfoList.begin(); it1 != indexFileMetaInfoList.end(); it1++)
								{
									char str[256];
									memset(str,'\0',256);
									for(int i = 0; (*it1).originalFileName[i]; i++)
										str[ i ] = tolower((*it1).originalFileName[i]);
									//char str[] = toupper((*it1).originalFileName);
							//		printf("List fileName is : %s\n",str);
									if(strcmp(fileName,str)==0)
									{
										map<int,string>::iterator it2;
										numFileId = (*it1).numFileName;
										it2 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it2).second.c_str();
							//			printf("File found at origin with index : %d. and fileid is :\n",numFileId);
										
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										memcpy(&(respBuf[datalength]),&metaFileSize,4);
										datalength += 4;
										
										
										memcpy(&(respBuf[datalength]),&tempFileID[0],20);
										datalength += 20;
										//datalength += strlen(tempFileID);
										char fileBuffer[8192];
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(fileBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
										//printf("Length of insertSearchResponseMap.fileMetaBuffer is %d\n",strlen(insertSearchResponseMap.fileMetaBuffer));
										fclose(temp);	
										memcpy(&(respBuf[datalength]),&fileBuffer[0],metaFileSize);
										datalength += metaFileSize;
										cacheFileNumber.insert(pair<int,bool>(numFileId,true));										

									}
								}
								pthread_mutex_unlock(&indexMutex);

							}
							else if (itemFromQueue.dataBuf[0]==0x02)
							{
								//TODO: Write the status file data for the req initiating node.
						//		printf("EVENT DISPATCHER: Sending Search response for sha1 : %s\n",(itemFromQueue.dataBuf+1));
								char sha1[41];
								memset(sha1,'\0',255);
								memcpy(&sha1[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
						//		printf("EVENT DISPATCHER: SHA1 is : %s\n",sha1);
								//compare sha1 values after converting into lower case
								pthread_mutex_lock(&indexMutex);
								multimap<string,int>::iterator it2;
								for(it2=indexSHA1Map.begin();it2!=indexSHA1Map.end();it2++)
								{		
									//it2 = indexSHA1Map.find(sha1);
									if(strcmp((const char*)(*it2).first.c_str(),sha1)==0)
									{
								//	printf("SHA1 found in the map.\n");
									//printf("File found at origin.\n");
										//searchResponseInfo insertSearchResponseMap;
										//insertSearchResponseMap.isOrigin = true;
										numFileId = (*it2).second;
										map<int,string>::iterator it3;
										it3 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it3).second.c_str();
								//		printf("File found at origin with index : %d. and fileid is :\n",numFileId);

										
										
										
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										memcpy(&(respBuf[datalength]),&metaFileSize,4);
										datalength += 4;
										
										
										memcpy(&(respBuf[datalength]),&tempFileID[0],20);
										datalength += 20;
										//datalength += strlen(tempFileID);
										char fileBuffer[8192];
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(fileBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
										//printf("Length of insertSearchResponseMap.fileMetaBuffer is %d\n",strlen(insertSearchResponseMap.fileMetaBuffer));
										fclose(temp);	
										memcpy(&(respBuf[datalength]),&fileBuffer[0],metaFileSize);
										datalength += metaFileSize;

										cacheFileNumber.insert(pair<int,bool>(numFileId,true));

									}
								}
								pthread_mutex_unlock(&indexMutex);


							}
							else if (itemFromQueue.dataBuf[0]==0x03)
							{
							//	printf("EVENT DISPATCHER: Sending Search response for keywords : %s\n",(itemFromQueue.dataBuf+1));
								char keywords[8192];
								memset(keywords,'\0',8192);
								memcpy(&keywords[0],&itemFromQueue.dataBuf[1],strlen(itemFromQueue.dataBuf)-1);
							//	printf("EVENT DISPATCHER: Keywords are : %s\n",keywords);
								
								//---------------------------------------------------------
								//create bitvector from given keyword.
								//---------------------------------------------------------
									/*printf("Bit Vector is:\n\n");
										for(int k=0;k<128;k++)
										{
											printf("%x",searchFileBitVector[k]);
										}
										printf("\n");
									*/
									char *result = NULL;
									result = strtok( keywords, " ");
									unsigned char searchFileBitVector[128];
									memset(&searchFileBitVector[0],0x00,128);
										while( result != NULL )
										{
											//printf( "result is \"%s\" with length %d\n", result,strlen(result) );
											
											char key[512];
											memset(key, '\0',512);
											memcpy(&key[0],&result[0],strlen(result));

											unsigned char sha[20];	//20 bytes
											unsigned char md5[16];	//16 bytes

											int sha1Index;
											int md5Index;

											

											
											MD5_CTX c;
											MD5_Init(&c);
											int len = strlen(key);
											MD5_Update(&c,(void *)key,len);
											
											
											MD5_Final(&md5[0], &c);
											//printf("Calculated MD5: ");
											//	for(unsigned int i=0; i<16;i++)
											//	{
											//		printf("%x",md5[i]);
											//	}
											//	printf("\n");

											/*MD5((unsigned char*)key,len,md5);
											printf("Calculated MD5: ");
												for(unsigned int i=0; i<17;i++)
												{
													printf("%x",md5[i]);
												}
												printf("\n");
											*/


											if ((0x01 & md5[14]) != 0x00)
											{
												md5Index = 256+ (unsigned int)md5[15];
											//		printf("md5Index : %d and md5[15]= %d, %02x\n", md5Index, md5[15], md5[15]);
												
											}
											else{
												md5Index = (unsigned int)md5[15];
												
											//		printf("md5Index : %d\n", md5Index);
												
											}

											
											SHA_CTX c1;
											SHA1_Init(&c1);
											SHA1_Update(&c1,(void *)key,len);
											SHA1_Final(&sha[0], &c1);
											//printf("Calculated SHA1: ");
											//	for(unsigned int i=0; i<20;i++)
											//	{
											//		printf("%x",sha[i]);
											//	}
											//	printf("\n");
											if ((0x01 & sha[18]) != 0x00)
											{
												sha1Index = 256+ (unsigned int)sha[19] +512;
										//			printf("sha1Index : %d and sha[19]= %d, %02x\n", sha1Index, sha[19], sha[19]);
												
											}
											else{
												sha1Index = (unsigned int)sha[19]+512;
												
										//			printf("sha1Index : %d\n", sha1Index);
												
											}

										//	printf("\nBITVECTOR indexes: %d --> %d\n",sha1Index,md5Index);
											if(md5Index<1024)
											{
												//md5Index=0;
												int bitVectorIndex=127- ceil(md5Index/8) ;
												int rem= ((md5Index)%8);
												searchFileBitVector[bitVectorIndex]=searchFileBitVector[bitVectorIndex] | ((unsigned int)1 << rem);
										//		printf("bitIndexis %d rem is %d\n",bitVectorIndex,rem);
											}
											if(sha1Index<1024)
											{
												//sha1Index=8;
												int bitVectorIndex=127- ceil(sha1Index/8);
												int rem= ((sha1Index)%8);
												searchFileBitVector[bitVectorIndex]=searchFileBitVector[bitVectorIndex] | ((unsigned int)1 << rem);
										//		printf("bitIndexis %d rem is %d\n",bitVectorIndex,rem);
											}
										/**	printf("Bit Vector is:\n\n");
											for(int k=0;k<128;k++)
											{
												printf("%x",searchFileBitVector[k]);
											}
											printf("\n");
											*/
											result = strtok( NULL, " " );
										}
										char formattedBitVector[257];
										memset(&formattedBitVector[0],'\0',257);
										for (int i =0 ;i< 128 ;i++)
										{
											unsigned char change[3] = {0};
											sprintf((char*)change, "%2.2x", searchFileBitVector[i]);
											sprintf((char*)formattedBitVector+2*i,"%s",change);
										}
								//		printf("%s\n",formattedBitVector);
								//		printf("##########################################\n");


								//----------------------------------------------------------
								//iterate over bitVector list and compare both bitVectors
								//----------------------------------------------------------
								pthread_mutex_lock(&indexMutex);
								list<bitVectorIndexItem>::iterator it5;
								char compareBitVector[257];
								bool matchBitVectorFlag = true;
								//printf("indexBitVectoreList length = %d\n",indexBitVectoreList.size());
								for(it5 = indexBitVectoreList.begin(); it5!=indexBitVectoreList.end();it5++)
								{
									matchBitVectorFlag = true;
									memcpy(&compareBitVector[0],&((*it5).indexBitVector[0]),strlen((*it5).indexBitVector));
								//	printf("%s\n",compareBitVector);
								//	printf("---------------------------------------\n");
									for(int k=0;k<(int)strlen(compareBitVector);k++)
									{
										int formatedIntValue = charHexLookupConverter(formattedBitVector[k]);
										int compareIntValue = charHexLookupConverter(compareBitVector[k]);
										//printf("Int value is [%d  %d]\n", a,b);

										if ((formatedIntValue & compareIntValue) != formatedIntValue)
										{
											//printf("AND fail\n");
											matchBitVectorFlag = false;
											break;
										}
										//printf("k = %d ----> [%d]--------[%d]\n",k,a,b);
									}
									if(matchBitVectorFlag == true)
									{
										
									//	printf("Both bitvectors matched...\n");
									//	searchResponseInfo insertSearchResponseMap;
									//	insertSearchResponseMap.isOrigin = true;
										map<int,string>::iterator it6;
										numFileId = (*it5).numFileName;
										it6 = numToFileIdMap.find(numFileId);
										char* tempFileID = (char*)(*it6).second.c_str();
									//	printf("File found at node with index : %d.\n",numFileId);
										
										//Read corresponsding meta file and fill the buffer.
										//Read corresponsding meta file and fill the buffer.
										char appendMFileName[256];
										memset(&appendMFileName[0],'\0',256);
										sprintf(appendMFileName, "/%d.meta", numFileId);

										char newNumMetaFile[256];
										memset(newNumMetaFile, '\0', 256);	
										memcpy(newNumMetaFile,homeDir,strlen(homeDir));
										strcat(newNumMetaFile,"/files");
										strcat(newNumMetaFile,appendMFileName);

										struct stat statistics1;
										int status1;
										status1 = stat((char*)newNumMetaFile,&statistics1);
										if(status1<0)
										{
											//printf("File does not exist.\n");
										}
										unsigned int metaFileSize = statistics1.st_size;
										memcpy(&(respBuf[datalength]),&metaFileSize,4);
										datalength += 4;
										
									//	printf("File %s has size: %d\n",newNumMetaFile,metaFileSize);

										memcpy(&(respBuf[datalength]),&tempFileID[0],20);
										datalength += 20;
										//datalength += strlen(tempFileID);
										char fileBuffer[8192];
										FILE* temp= fopen(newNumMetaFile,"r");
										int read = fread(fileBuffer,1,metaFileSize,temp);	
										if(read == -1)
										{
											
											//printf("EVENT DISPATCHER: Error Reading META FILE\n");
										}
									//	//printf("Length of fileBuffer is %d\n",strlen(fileBuffer));
										fclose(temp);	
										memcpy(&(respBuf[datalength]),&fileBuffer[0],metaFileSize);
										datalength += metaFileSize;	
										cacheFileNumber.insert(pair<int,bool>(numFileId,true));
										
										
										
									}
									else
									{
							//			printf("\nNot matched...\n");
									}

								}
								pthread_mutex_unlock(&indexMutex);

							}
							else
							{
								//printf("Wrong message type detected on status req packet..\n");
							}

								/*pthread_mutex_lock(&indexMutex);
								map<int,searchResponseInfo>::iterator it8;
								for(it8 = indexSearchResponseMap.begin(); it8!=indexSearchResponseMap.end();it8++)
								{
									printf("Here.... %d ---> %s and isOrigin flag : \n",(*it8).first,(*it8).second.originalFileName);
									cout<<(*it8).second.isOrigin<<endl;
								}
								pthread_mutex_unlock(&indexMutex);*/
								
								//Update Cache file using LRU
										pthread_mutex_lock(&indexMutex);
										list<indexFileMetaInfo>::iterator it11;	
										for(it11=indexFileMetaInfoList.begin();it11!=indexFileMetaInfoList.end();it11++)
										{
											if((*it11).isInCache)
											{
												int temp = (*it11).numFileName;
												map<int,bool>::iterator it = cacheFileNumber.find(temp);
												if(it != cacheFileNumber.end())
												{
													indexFileMetaInfo updateCacheInfo;
													memcpy(&updateCacheInfo.originalFileName[0],&(*it11).originalFileName[0],(int)strlen((*it11).originalFileName));
													memcpy(&updateCacheInfo.fileID[0],&(*it11).fileID[0],(int)strlen((const char*)(*it11).fileID));
													memcpy(&updateCacheInfo.filePassword[0],&(*it11).filePassword[0],(int)strlen((*it11).filePassword));
													memcpy(&updateCacheInfo.fileNonceValue[0],&(*it11).fileNonceValue[0],(int)strlen((const char*)(*it11).fileNonceValue));
													updateCacheInfo.numFileName = (*it11).numFileName;
													updateCacheInfo.isInCache = (*it11).isInCache;
													indexFileMetaInfoList.erase(it11);
													cacheFileNumber.erase(it);
													indexFileMetaInfoList.push_back(updateCacheInfo);
												}
											}

										}

										pthread_mutex_unlock(&indexMutex);

							memcpy(&(searchRespToBePushed.dataBuf[0]),&(respBuf[0]),datalength);
							searchRespToBePushed.msgHeader.msgDataLength=datalength;
						//	printf("DATA LENGTH OF SEARCH RESP is %d\n",datalength);
							pthread_mutex_lock(&sockIndexMapMutex);
							int index=sockFDToQIndexMap[itemFromQueue.sockfd];
								pthread_mutex_lock(&wrtieQMutex[index]);
									wrtieThreadQueue[index].push_back(searchRespToBePushed);
									//printf("EVENT DISPATCHER: STATUS RESPONSE MSG: Msg pushed to writeQueue of %d\n",index);
									pthread_cond_broadcast(&wrtieQCV[index]);

								pthread_mutex_unlock(&wrtieQMutex[index]);								
							pthread_mutex_unlock(&sockIndexMapMutex);

					

							//log for sending SHRS.
							
						pthread_mutex_lock(&connectedNodeListMutex);
								uint16_t portTemp=0;
								char *tempHost=(char*)malloc(512);
								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
													memset(&str1[0],'\0',512);
													memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

													char *str=(char*)malloc(512);
													memset(str,'\0',512);
													memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
						pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "s  %s %s:%hu SHRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(searchRespToBePushed.msgHeader.msgDataLength+27),
											(unsigned char)searchRespToBePushed.msgHeader.ttlInHeader,
											(unsigned char)searchRespToBePushed.msgHeader.UOID[16],
											(unsigned char)searchRespToBePushed.msgHeader.UOID[17],
											(unsigned char)searchRespToBePushed.msgHeader.UOID[18],
											(unsigned char)searchRespToBePushed.msgHeader.UOID[19],
											(unsigned char)searchRespToBePushed.dataBuf[16],
											(unsigned char)searchRespToBePushed.dataBuf[17],
											(unsigned char)searchRespToBePushed.dataBuf[18],
											(unsigned char)searchRespToBePushed.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);


						}

				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:STATUS REQUEST The msg already exists in the map.DO NOT FORWARD!!!!\n");
					continue;
				}

			}// End of SEARCH REQUEST message.
			else if(itemFromQueue.msgHeader.messageType==0xEB)       //Search RESP MSG
			{
			//printf("Search Resp msg detected.\n");
				// logging into log file here...
				
							pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "r  %s %s:%hu SHRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);


				map<string,msgLifeTimeClass>::iterator uoidIterator2;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator2=UOIDMsgLifeTimeMap.find(str);
				if(uoidIterator2 == UOIDMsgLifeTimeMap.end())
				{	

						//Entry not found in the map.. make a new entry in the map for it. and continue to process the msg.
						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid ((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string, msgLifeTimeClass>(uoid, newEntry));
						

						unsigned char uoidFromItemData[20];
						memcpy(&uoidFromItemData[0],&(itemFromQueue.dataBuf[0]),20);
						string str1 ((const char*)uoidFromItemData,20);
						uoidIterator2=UOIDMsgLifeTimeMap.find(str1);

						if(uoidIterator2==UOIDMsgLifeTimeMap.end())
						{
						
							//NOT FOUND
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							//printf("EVENT DISPATCHER: STATUS RESPONSE. THERE HAS NOT BEEN ANY STATUS REQ FOR THIS UOID.\n\n");
						
						}
						else
						{
							//Found in the UOID MAP.
							int index=-1;
							msgLifeTimeClass tmp=(*uoidIterator2).second;
							pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
							if(tmp.sockOfMsgReciept== -1)
							{
				//				printf("\nI have reached origin node...: %d\n",itemFromQueue.msgHeader.msgDataLength);
								//printf();

									int length=20;
									pthread_mutex_lock(&cntrlCFlagMutex);
									if(!cntrlCFlag)
									{
										pthread_mutex_lock(&indexMutex);
									while(length!=(int)itemFromQueue.msgHeader.msgDataLength)
									{
										
										searchResponseInfo insertSearchResponseMap;
										insertSearchResponseMap.isOrigin = false;
										int metaLength = 0;
										memcpy(&metaLength,&(itemFromQueue.dataBuf[length]),4);
										//printf("\nMetadata Length : %d and searchIndex: %d\n",metaLength,searchIndex);
										//cout<<"ORIGIN Flag :"<<insertSearchResponseMap.isOrigin<<endl;
										length+=4;
										memcpy(&insertSearchResponseMap.fileID[0],&(itemFromQueue.dataBuf[length]),20);
										length+=20;
										memcpy(&insertSearchResponseMap.fileMetaBuffer[0],&(itemFromQueue.dataBuf[length]),metaLength);
										length+=metaLength;
										//printf("\ninsertSearchResponseMap.fileMetaBuffer length : %d and searchIndex: %d\n",strlen(insertSearchResponseMap.fileMetaBuffer),searchIndex);
										//cout<<"ORIGIN Flag :"<<insertSearchResponseMap.isOrigin<<endl;
										//memcpy(&insertSearchResponseMap.fileID[0],&tempFileID[0],strlen(tempFileID));
										//memcpy(&insertSearchResponseMap.originalFileName[0],&str[0],strlen(str));
										
										
										indexSearchResponseMap.insert(pair<int,searchResponseInfo>(searchIndex,insertSearchResponseMap));
										//printUOID((unsigned char *)(*it2).second.c_str());
										searchIndex++;
									}
									pthread_mutex_unlock(&indexMutex);
									}
									pthread_mutex_unlock(&cntrlCFlagMutex);
										
							}
							else
							{
								pthread_mutex_lock(&sockIndexMapMutex);
								 index=sockFDToQIndexMap[tmp.sockOfMsgReciept];
								 pthread_mutex_lock(&wrtieQMutex[index]);
										//printf("EVENT DISPATCHER: JOIN RESP msgtype %x and buffer is %s",msgToBePushed.msgHeader,);
										wrtieThreadQueue[index].push_back(itemFromQueue);
										//printf("EVENT DISPATCHER: STATUS RESP: Msg pushed to writeQueue of %d\n",index);
										pthread_cond_broadcast(&wrtieQCV[index]);

								 pthread_mutex_unlock(&wrtieQMutex[index]);	
								pthread_mutex_unlock(&sockIndexMapMutex);




								pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==tmp.sockOfMsgReciept)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "f  %s %s:%hu SHRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);







							}
							
						}
				}
				else
				{
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					//printf("EVENT DISPATCHER:STATUS RESPONSE The msg already exists in the map.DO NOT FORWARD!!!!\n");
					//exit(0);
					continue;  //Think abt this. Whether to put continue or exit(0);
				}
				
				
			}// End of SEARCH RESP message.

			
			else if(itemFromQueue.msgHeader.messageType==0xDC)
			{
				//printf("GET REQ detected.\n");
				// enter UOID
				// check if from sock = -1
				//if not check if requested file in on node.     If on -1 just flood to all write thread.
				// if file on nodedo not flood and send get response.












					if(itemFromQueue.sockfd!=-1)
					{
					
						//logging SHRQ into file.
						pthread_mutex_lock(&connectedNodeListMutex);
							uint16_t portTemp=0;
							char *tempHost=(char*)malloc(512);
							map<string,int>::iterator it;
						for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
						{
							//printf("\n------->%d<-----%d----\n",(*it).second,itemFromQueue.sockfd);
							if((*it).second==itemFromQueue.sockfd)
							{
										char* str1 = (char*) malloc(512); 
										memset(&str1[0],'\0',512);
										memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

										char *str=(char*)malloc(512);
										memset(str,'\0',512);
										memcpy(&str[0],&str1[0],strlen(str1));
										//printf("String from list is %s\n",str);
										
										tempHost=strtok(str,"_");
										//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
										char *tempPort=strtok(NULL,"_");
										//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
										
										portTemp=atoi(tempPort);
										break;
							}
						
						}
						pthread_mutex_unlock(&connectedNodeListMutex);



						pthread_mutex_lock(&logFileMutex);
							

							gettimeofday(&tv, NULL); 
							int sec = tv.tv_sec ;
							int msec = tv.tv_usec/1000;
							char *time = (char *)malloc(14);
							memset(time,0,14);
							sprintf(time,"%10ld.%03d",(long)sec,msec);
							time[strlen(time)]='\0';
							fprintf(logFilePtr, "r  %s %s:%hu GTRQ %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
									tempHost, portTemp,
									(itemFromQueue.msgHeader.msgDataLength+27),
									(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
									(unsigned char)itemFromQueue.msgHeader.UOID[16],
									(unsigned char)itemFromQueue.msgHeader.UOID[17],
									(unsigned char)itemFromQueue.msgHeader.UOID[18],
									(unsigned char)itemFromQueue.msgHeader.UOID[19],
									(unsigned char)itemFromQueue.dataBuf[16],
									(unsigned char)itemFromQueue.dataBuf[17],
									(unsigned char)itemFromQueue.dataBuf[18],
									(unsigned char)itemFromQueue.dataBuf[19]);
							pthread_mutex_unlock(&logFileMutex);
					}














				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator=UOIDMsgLifeTimeMap.find(str);

				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{

						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));

						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);


						char getReqFileUOID[21];
						memset(&getReqFileUOID[0],'\0',21);
						memcpy(&getReqFileUOID[0],&itemFromQueue.dataBuf[0],20);
						bool activateFlooding=false;

						int fileNumberToBeSent=-1;
						bool fileFoundSendResp=false;
						//int sizeOfFileToBeSent=-1;
						if(itemFromQueue.sockfd != -1)
						{
							// Check if requested file is on node. if Yes send GETRESP




									list<indexFileMetaInfo>:: iterator flistIt;
									pthread_mutex_lock(&indexMutex);
									for(flistIt=indexFileMetaInfoList.begin();flistIt!=indexFileMetaInfoList.end();flistIt++)
									{
										if(!(strncmp((char*)(*flistIt).fileID,(char*)getReqFileUOID,20)))
										{
											fileFoundSendResp=true;
											fileNumberToBeSent=(*flistIt).numFileName;
											//sizeOfFileToBeSent=(*flistIt).filesize;
											if((*flistIt).isInCache)
											{
											(*flistIt).isInCache=false;

											remainingCacheSizeInBytes+=(*flistIt).filesize;
											}
											break;
										}

									}//end of for
									pthread_mutex_unlock(&indexMutex);
									if(fileFoundSendResp)
									{
											msgHeaderClass getRespMsgHeader;
											queueItem msgToInsertInWrite;

											getRespMsgHeader.messageType=0xDB;
											unsigned char *buff2;
											char* msg1 = (char*)"GTRS";	
											buff2=GetUOID((char *)nodeInstanceId,msg1,buf, sizeof(buf));
											memcpy(getRespMsgHeader.UOID,buf,20);
											getRespMsgHeader.ttlInHeader=255;
											msgToInsertInWrite.sockfd=itemFromQueue.sockfd;
											msgToInsertInWrite.msgHeader=getRespMsgHeader;
											memcpy(&msgToInsertInWrite.dataBuf[0],&itemFromQueue.msgHeader.UOID[0],20);
											msgToInsertInWrite.dataBuf[20] = (char)fileNumberToBeSent;
											msgToInsertInWrite.dataBuf[21] = (char)' ';
											msgToInsertInWrite.dataBuf[22] = (char)'0';
											
											
											char appendDFileName[256];
											char appendMFileName[256];
											char newNumMetaFile[256];
											char newNumDataFile[256];

											memset(&newNumMetaFile[0],'\0',256);
											memset(&newNumDataFile[0],'\0',256);

											memset(&appendMFileName[0],'\0',256);
											memset(&appendDFileName[0],'\0',256);

											sprintf(appendDFileName, "/%d.data", fileNumberToBeSent);
											sprintf(appendMFileName, "/%d.meta", fileNumberToBeSent);

											memcpy(newNumMetaFile,homeDir,strlen(homeDir));
											strcat(newNumMetaFile,"/files");
											strcat(newNumMetaFile,appendMFileName);

											memcpy(newNumDataFile,homeDir,strlen(homeDir));
											strcat(newNumDataFile,"/files");
											strcat(newNumDataFile,appendDFileName);
										
											
											struct stat statistics;
											int status;
											status = stat((char*)newNumDataFile,&statistics);
											if(status<0)
											{
												//printf("WRITE THREAD: File does not exist.\n");
											}
											unsigned int filesize = statistics.st_size;
											
											struct stat statistics1;
											int status1;
											status1 = stat((char*)newNumMetaFile,&statistics1);
											if(status1<0)
											{
												//printf("WRITE THREAD: File does not exist.\n");
											}
											unsigned int metaFileSize = statistics1.st_size;
											
											msgToInsertInWrite.msgHeader.msgDataLength=metaFileSize+filesize+24;



											pthread_mutex_lock(&sockIndexMapMutex);
												int index=sockFDToQIndexMap[itemFromQueue.sockfd];
													pthread_mutex_lock(&wrtieQMutex[index]);
									//					printf("DISPATCHER Get Response: Will push %s data in queue.\n\n",msgToInsertInWrite.dataBuf);
														wrtieThreadQueue[index].push_back(msgToInsertInWrite);
									//					printf("EVENT DISPATCHER: GET RESP MSG: Msg pushed to writeQueue of %d\n",index);
														pthread_cond_broadcast(&wrtieQCV[index]);

													pthread_mutex_unlock(&wrtieQMutex[index]);								
												pthread_mutex_unlock(&sockIndexMapMutex);
											








													
								pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
								pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "f  %s %s:%hu GTRS %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19],
											(unsigned char)itemFromQueue.dataBuf[16],
											(unsigned char)itemFromQueue.dataBuf[17],
											(unsigned char)itemFromQueue.dataBuf[18],
											(unsigned char)itemFromQueue.dataBuf[19]);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);















									}
									else
									{
							//			printf("File not found. so activate flooding. \n");
										activateFlooding=true;
									}



						}
						else
						{
							activateFlooding=true;
						}
						
						if(activateFlooding)
						{
						//	printf("Now flooding... \n");
							
								msgToBePushed.sockfd=itemFromQueue.sockfd;
								//populate the header as the same only changing the TTL value.
								msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
								memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
								//Decrease TTL by 1 is ttl in header less than node ttl
								//else set node ttl as the new ttl ..
								if((itemFromQueue.msgHeader.ttlInHeader-1)<ttl)
								{
									msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
								}
								else
								{
									msgToBePushed.msgHeader.ttlInHeader=ttl;	
								}

								msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
								//Copy Data from itemfromqueue into new quueue item.
								memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
								//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
								//forward the msg to other nodes if the new ttl>0
								if(msgToBePushed.msgHeader.ttlInHeader!=0)
								{
									//Find index of writeQueue from map for all entries in connectedNodeList
									map<string,int>::iterator conNodeListIterator;
									//printf("---------------2--------------\n");
									pthread_mutex_lock(&connectedNodeListMutex);
									//printf("---------------4--------------\n");
									for ( conNodeListIterator=connectedNodeList.begin() ; conNodeListIterator != connectedNodeList.end(); conNodeListIterator++ )
									{

										uint16_t portTemp=0;
										char *tempHost=(char*)malloc(512);

										//printf("---------------5--------------\n");
										int socket=(*conNodeListIterator).second;
										//printf("---------------5--------------%d\n",socket);
										if(socket!=itemFromQueue.sockfd)
										{
													//printf("---------------6--------------\n");
													pthread_mutex_lock(&sockIndexMapMutex);
													int index=sockFDToQIndexMap[socket];
														pthread_mutex_lock(&wrtieQMutex[index]);
														//	printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
															wrtieThreadQueue[index].push_back(msgToBePushed);
															//printf("EVENT DISPATCHER: JOIN MSG: Msg pushed to writeQueue of %d\n",index);
															pthread_cond_broadcast(&wrtieQCV[index]);

														pthread_mutex_unlock(&wrtieQMutex[index]);								
													pthread_mutex_unlock(&sockIndexMapMutex);

												//}
												//printf("---------------7--------------\n");
											//}
									
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*conNodeListIterator).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												
												//}




											pthread_mutex_lock(&logFileMutex);
											uint16_t tempport=0;
											memcpy(&tempport,&itemFromQueue.dataBuf[4],sizeof(uint16_t));
											char temphost1[20];
											memset(&temphost1[0],'\0',20);
											memcpy(&temphost1[0],&itemFromQueue.dataBuf[6],strlen(myHostName));

											gettimeofday(&tv, NULL); 
											int sec = tv.tv_sec ;
											int msec = tv.tv_usec/1000;
											char *time = (char *)malloc(14);
											memset(time,0,14);
											sprintf(time,"%10ld.%03d",(long)sec,msec);
											time[strlen(time)]='\0';
											fprintf(logFilePtr, "f  %s %s:%hu GTRQ %d 0x%02x %x%x%x%x %x%x%x%x\n",time,
													tempHost, portTemp,
													(msgToBePushed.msgHeader.msgDataLength+27),
													(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
													(unsigned char)msgToBePushed.msgHeader.UOID[16],
													(unsigned char)msgToBePushed.msgHeader.UOID[17],
													(unsigned char)msgToBePushed.msgHeader.UOID[18],
													(unsigned char)msgToBePushed.msgHeader.UOID[19],
													(unsigned char)msgToBePushed.dataBuf[16],
													(unsigned char)msgToBePushed.dataBuf[17],
													(unsigned char)msgToBePushed.dataBuf[18],
													(unsigned char)msgToBePushed.dataBuf[19]);
											pthread_mutex_unlock(&logFileMutex);
										}
									}






									pthread_mutex_unlock(&connectedNodeListMutex);
								}//end of ttl if

						}//end of activateflood if



				}//end of UOID if
				else
				{
			//		printf("Packet Dropped.\n");
			pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					continue;
				
				}













			}

			else if(itemFromQueue.msgHeader.messageType==0xBC)
			{
			
				//printf("DELETE Recieved.\n");
					if(itemFromQueue.sockfd!=-1)
					{
							pthread_mutex_lock(&connectedNodeListMutex);
									uint16_t portTemp=0;
									char *tempHost=(char*)malloc(512);

								map<string,int>::iterator it;
								for(it=connectedNodeList.begin() ; it != connectedNodeList.end(); it++ )
								{
									if((*it).second==itemFromQueue.sockfd)
									{
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*it).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												break;
									}
								
								}
				pthread_mutex_unlock(&connectedNodeListMutex);

									pthread_mutex_lock(&logFileMutex);

										gettimeofday(&tv, NULL); 
										int sec = tv.tv_sec ;
										int msec = tv.tv_usec/1000;
										char *time = (char *)malloc(14);
										memset(time,0,14);
										sprintf(time,"%10ld.%03d",(long)sec,msec);
										time[strlen(time)]='\0';

										



										fprintf(logFilePtr, "r  %s %s:%hu DELT %d 0x%02x %x%x%x%x\n",time,
											tempHost,
											portTemp,
											(itemFromQueue.msgHeader.msgDataLength+27),
											(unsigned char)itemFromQueue.msgHeader.ttlInHeader,
											(unsigned char)itemFromQueue.msgHeader.UOID[16],
											(unsigned char)itemFromQueue.msgHeader.UOID[17],
											(unsigned char)itemFromQueue.msgHeader.UOID[18],
											(unsigned char)itemFromQueue.msgHeader.UOID[19]
											);
											//helloRecvData.HostPort,helloRecvData.Hostname);
										pthread_mutex_unlock(&logFileMutex);



							}
















				map<string,msgLifeTimeClass>::iterator uoidIterator;
				string str ((const char*)itemFromQueue.msgHeader.UOID,20);

				pthread_mutex_lock(&UOIDMsgLifeTimeMapMutex);
				uoidIterator=UOIDMsgLifeTimeMap.find(str);

				if(uoidIterator == UOIDMsgLifeTimeMap.end())
				{

						unsigned char uoidToInsertInMap[20];
						memcpy(&uoidToInsertInMap[0],itemFromQueue.msgHeader.UOID,20);
						string uoid((const char*)uoidToInsertInMap,20);
						msgLifeTimeClass newEntry(itemFromQueue.sockfd,msgLifeTime);
						//newEntry.sockOfMsgReciept=itemFromQueue.sockfd;
						//newEntry.msgLifeTimeValue=msgLifeTime;
						UOIDMsgLifeTimeMap.insert(pair<string,msgLifeTimeClass>(uoid,newEntry));

						pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);

						if(itemFromQueue.sockfd != -1)
						{
								char info[1024];
								memset(info,'\0',1024);
								memcpy(&info[0],&itemFromQueue.dataBuf[0],itemFromQueue.msgHeader.msgDataLength);
								//Now we will decode this 
								char *line1 = strtok(info,"\n");
								char *line2 = strtok(NULL,"\n");
								char *line3 = strtok(NULL,"\n");
								char *line4 = strtok(NULL,"\n");
								
								bool permFileAlreadyExist=false;
								char *fname = strtok(line1,"=");
								if(fname)
								{}
								char *delname = strtok(NULL,"=");

								char *sha1 = strtok(line2,"=");
								if(sha1)
								{}
								char *delsha1 = strtok(NULL,"=");
								if(delsha1)
								{}
								char *nonce = strtok(line3,"=");
								if(nonce)
								{}
								char *delnonce = strtok(NULL,"=");

								char *password = strtok(line4,"=");
								if(password){};
								char *delpass = strtok(NULL,"=");

								unsigned char deleteNonce[20];
								memset(&deleteNonce[0],'\0',20);
								bool deleteOnCurrentNode =false;
								
								
								//printf("Password Recieved is %s\n",delpass);
								bool  blah=true;
								if(delpass[0] == 'g')
								{
										blah=false;
										//printf("\nPassword is not the original password.");
								}
								SHA1((unsigned char*)delpass, 20, deleteNonce);
								char formattedNonce[41];
								memset(&formattedNonce[0],'\0',41);
								for (int i =0 ;i< 20 ;i++)
								{
									unsigned char change[3] = {0};
									sprintf((char*)change, "%2.2x", deleteNonce[i]);
									sprintf((char*)formattedNonce+2*i,"%s",change);
								}
								char formattedSha1[41];
								memset(&formattedSha1[0],'\0',41);
								//printf("Del Sha1 reiceved is %s",delsha1);
								for (int i =0 ;i< 20 ;i++)
								{
									unsigned char change[3] = {0};
									sprintf((char*)change, "%2.2x", delsha1[i]);
									sprintf((char*)formattedSha1+2*i,"%s",change);
								}
								if(blah == true)
								{
									pthread_mutex_lock(&indexMutex);
										list<indexFileMetaInfo>::iterator it;
									
									
										//bool activateFlooding=false;
										//char passwordForDelete[21];
										//memset(&passwordForDelete[0],'\0',21);
										multimap<string,int>:: iterator it1;
									//printf("Formatted Nonce is %s\n Stored nonce is %s\n",formattedNonce,delnonce);
									if(strncmp(formattedNonce,delnonce,40)==0)
									{
										deleteOnCurrentNode=true;
									}
									if(deleteOnCurrentNode)
									{
										
										//printf("\nInside blah = true & \n");			


										for(it=indexFileMetaInfoList.begin();it!=indexFileMetaInfoList.end();it++)
										{
											//printf("DeleteName:[%s]  FileName:[%s]\n",delname,(*it).originalFileName);
											//printf("DeleteNonce:[%s]  Nonce:[%s]\n",formattedNonce,(*it).fileNonceValue);
											
											//printf("=========================================================================\n");
											if ((strcmp(delname,(*it).originalFileName)==0) && ((strcmp((char*)(*it).fileNonceValue,formattedNonce)==0)))
											{
															//printf("Compared true=====================\n");

													for(it1=indexSHA1Map.begin();it1!=indexSHA1Map.end();it1++)
													{		
														//it2 = indexSHA1Map.find(sha1);
														//printf("==============================\nDeleteNumber:[%d]  FileNunber:[%d]\n",(*it1).second,(*it).numFileName);
														//printf("DeleteSha1:[%s]  SHA1:[%s]\n============================\n",delsha1,(*it1).first.c_str());

														if(strcmp((const char*)(*it1).first.c_str(),delsha1)==0 && ((*it1).second==(*it).numFileName) )
														{
															//printf("File Found\n");
															//	it1=indexSHA1Map.find(str1);
															permFileAlreadyExist=true;
															/*if((*it).filePassword[0] != '\0')
															{
																passexist=true;
																memcpy(&passwordForDelete[0],&((*it).filePassword[0]),20);
															}
															*/

															break;
														}
													}
													if(permFileAlreadyExist)
													{

														break;
													}
										
															
											}
										}
										
									
								}
								if(permFileAlreadyExist)
								{
									//printf("Inside File delete...\n");
									char appendDFileName[256];
									char appendMFileName[256];
									memset(&appendMFileName[0],'\0',256);
									memset(&appendDFileName[0],'\0',256);

									//numfileId=numFileNameCounter++;

									sprintf(appendDFileName, "/%d.data", (*it).numFileName);
									sprintf(appendMFileName, "/%d.meta", (*it).numFileName);
									
									char newNumDataFile[256];
									char newNumMetaFile[256];
									memset(newNumDataFile, '\0', 256);
									memset(newNumMetaFile, '\0', 256);
									
									memcpy(newNumDataFile,homeDir,strlen(homeDir));
									strcat(newNumDataFile,"/files");
									
									//http://www.linuxquestions.org/questions/programming-9/mkdir-in-c-setting-wrong-permissions-613250/
									//mkdir(newNumDataFile,S_IRWXU | S_IRWXG | S_IRWXO);
									strcat(newNumDataFile,appendDFileName); //Change it to variable numebr file generated in indexing above
									

									memcpy(newNumMetaFile,homeDir,strlen(homeDir));
									strcat(newNumMetaFile,"/files");
									//mkdir(newNumMetaFile,S_IRWXU | S_IRWXG | S_IRWXO);
									//http://www.linuxquestions.org/questions/programming-9/mkdir-in-c-setting-wrong-permissions-613250/
									
									strcat(newNumMetaFile,appendMFileName); //Change it to variable numebr file generated in indexing above
					//				printf("DELETE: Data File Path is: %s\n",newNumDataFile);
					//				printf("DELETE: Meta File Path is: %s\n",newNumMetaFile);
										
									remove(newNumDataFile);
									remove(newNumMetaFile);

									//Retain the cache size if file is part of the Cache.
									if((*it).isInCache)
									{
										remainingCacheSizeInBytes+=(*it).filesize;
									}

									// Now delete all the index structures entries.
									
									map<int,searchResponseInfo>:: iterator searchIt;
									for(searchIt=indexSearchResponseMap.begin();searchIt != indexSearchResponseMap.end();searchIt++)
									{
										if( !strncmp((const char*)(*searchIt).second.fileID,(const char*)(*it).fileID,20))
										{
											indexSearchResponseMap.erase(searchIt);
											break;
										}
									}
									list<bitVectorIndexItem>:: iterator bvIt;
									for(bvIt=indexBitVectoreList.begin();bvIt != indexBitVectoreList.end();bvIt++)
									{
										if((*bvIt).numFileName == (*it).numFileName)
										{
											indexBitVectoreList.erase(bvIt);
											break;
										}
									}
									
									map<int,string>::iterator it3;
									
									it3=numToFileIdMap.find((*it).numFileName);
									numToFileIdMap.erase(it3);
									indexSHA1Map.erase(it1);
									indexFileMetaInfoList.erase(it);
									
								//printf("\n\nFile Deleted\n\n");








								
								}
								
								pthread_mutex_unlock(&indexMutex);


						}
						else
						{
							//printf("Not to delete the file...Fllod the request...\n");	
						}


				}








						msgToBePushed.sockfd=itemFromQueue.sockfd;
								//populate the header as the same only changing the TTL value.
								msgToBePushed.msgHeader.messageType=itemFromQueue.msgHeader.messageType;
								memcpy(msgToBePushed.msgHeader.UOID,itemFromQueue.msgHeader.UOID,20);
								//Decrease TTL by 1 is ttl in header less than node ttl
								//else set node ttl as the new ttl ..
								if((itemFromQueue.msgHeader.ttlInHeader-1)<ttl)
								{
									msgToBePushed.msgHeader.ttlInHeader=itemFromQueue.msgHeader.ttlInHeader-1;
								}
								else
								{
									msgToBePushed.msgHeader.ttlInHeader=ttl;	
								}

								msgToBePushed.msgHeader.msgDataLength=itemFromQueue.msgHeader.msgDataLength;
								//Copy Data from itemfromqueue into new quueue item.
								memcpy(&(msgToBePushed.dataBuf[0]),&(itemFromQueue.dataBuf[0]),itemFromQueue.msgHeader.msgDataLength);
								//printf("Will copy %s into %s\n\n",itemFromQueue.dataBuf,msgToBePushed.dataBuf);
								//forward the msg to other nodes if the new ttl>0
								if(msgToBePushed.msgHeader.ttlInHeader!=0)
								{
									//Find index of writeQueue from map for all entries in connectedNodeList
									map<string,int>::iterator conNodeListIterator;
									//printf("---------------2--------------\n");
									pthread_mutex_lock(&connectedNodeListMutex);
									//printf("---------------4--------------\n");
									for ( conNodeListIterator=connectedNodeList.begin() ; conNodeListIterator != connectedNodeList.end(); conNodeListIterator++ )
									{

										uint16_t portTemp=0;
											char *tempHost=(char*)malloc(512);

										//printf("---------------5--------------\n");
										int socket=(*conNodeListIterator).second;
										//printf("---------------5--------------%d\n",socket);
										if(socket!=itemFromQueue.sockfd)
										{
													//printf("---------------6--------------\n");
													pthread_mutex_lock(&sockIndexMapMutex);
													int index=sockFDToQIndexMap[socket];

														pthread_mutex_lock(&wrtieQMutex[index]);
														//	printf("DISPATCHER: Will push %s data in queue.\n\n",msgToBePushed.dataBuf);
															wrtieThreadQueue[index].push_back(msgToBePushed);
															//printf("EVENT DISPATCHER: JOIN MSG: Msg pushed to writeQueue of %d\n",index);
															pthread_cond_broadcast(&wrtieQCV[index]);

														pthread_mutex_unlock(&wrtieQMutex[index]);								
													pthread_mutex_unlock(&sockIndexMapMutex);

												//}
												//printf("---------------7--------------\n");
											//}
									
												char* str1 = (char*) malloc(512); 
												memset(&str1[0],'\0',512);
												memcpy(&str1[0],&(((*conNodeListIterator).first).c_str()[0]),19);

												char *str=(char*)malloc(512);
												memset(str,'\0',512);
												memcpy(&str[0],&str1[0],strlen(str1));
												//printf("String from list is %s\n",str);
												
												tempHost=strtok(str,"_");
												//printf("TempHost is %s and length is %d\n",tempHost,(int)strlen(tempHost));
												char *tempPort=strtok(NULL,"_");
												//printf("TempPort is %s and length is %d\n",tempPort,(int)strlen(tempPort));
												
												portTemp=atoi(tempPort);
												
												//}




											pthread_mutex_lock(&logFileMutex);
											uint16_t tempport=0;
											memcpy(&tempport,&itemFromQueue.dataBuf[4],sizeof(uint16_t));
											char temphost1[20];
											memset(&temphost1[0],'\0',20);
											memcpy(&temphost1[0],&itemFromQueue.dataBuf[6],strlen(myHostName));

											gettimeofday(&tv, NULL); 
											int sec = tv.tv_sec ;
											int msec = tv.tv_usec/1000;
											char *time = (char *)malloc(14);
											memset(time,0,14);
											sprintf(time,"%10ld.%03d",(long)sec,msec);
											time[strlen(time)]='\0';
											fprintf(logFilePtr, "f  %s %s:%hu DELT %d 0x%02x %x%x%x%x\n",time,
													tempHost, portTemp,
													(msgToBePushed.msgHeader.msgDataLength+27),
													(unsigned char)msgToBePushed.msgHeader.ttlInHeader,
													(unsigned char)msgToBePushed.msgHeader.UOID[16],
													(unsigned char)msgToBePushed.msgHeader.UOID[17],
													(unsigned char)msgToBePushed.msgHeader.UOID[18],
													(unsigned char)msgToBePushed.msgHeader.UOID[19]
													);
											pthread_mutex_unlock(&logFileMutex);
										}
									}

									pthread_mutex_unlock(&connectedNodeListMutex);


								}


							//printf("END of DELETE Request in dispatcher...\n");
						







				}
				else
				{
					//printf("Packet Dropped.\n");
					pthread_mutex_unlock(&UOIDMsgLifeTimeMapMutex);
					continue;
				
				
				}


			}
			else
			{
				printf("Unknown Msg Type.\n");
			}




	}//end of while(1)
	//printf("(((((((((((((((((((((((((((((((end of while))))))))))))))))))))))))))))\n");

}

